Home Blog Page 85

How to display JSON data in listview in android – HttpRequest using OkHttp android

0
Http Request using OkHttp android library – Display data in ListView Part 2

Hi Guys, Welcome to Proto Coders Point, if you have seen our last post on how to make an android http request call using okhttp android library, where we have just fetched data from the API which is in JSON format, and just displayed the response.body() in text view.

In this Tutorial post we will show/display the data received by okhttp call a http response data in Simple Listview Adapter.

DEMO SCREENSHOT

demo example on okhttp android library

Please check out the part 1 of OkHttp android library

In part one all the required dependencies is add.

Then, Let’s start implement okhttp android response data to display in listview.

Step1: Create a layout file

res > layout (right click) >New > Layout Resource File

create a new layout file and name it as listview_layout.xml and then paste the below layout design xml UI code.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">
    
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="120dp"
        android:weightSum="2"
        android:padding="2dp"
        android:layout_margin="10dp"
        android:orientation="vertical">
        <TextView
            android:id="@+id/name"
            android:text="Name"
            android:layout_marginTop="5dp"
            android:layout_marginBottom="5dp"
            android:layout_weight="0.5"
            android:textSize="18sp"
            android:textStyle="bold"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:textColor="@color/colorPrimary" />

        <TextView
            android:id="@+id/power"
            android:text="Power"
            android:layout_weight="0.5"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="#5d5d5d"
             />
    </LinearLayout>

</LinearLayout>

The above XML layout has 2 views Both are TextView which holds the name of superhero and power of the superhero.

don’t get confused i have a API of Superheros list which is in JSON format.

This is the URL of my API

https://protocoderspoint.com/jsondata/superheros.json

Step 2: adding listview in activity_main.xml

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <ListView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/listview"/>

</androidx.constraintlayout.widget.ConstraintLayout>

this is where the list of data will be shown using ListView

Step 3 : Final MainActivity.java

MainActivity.java

package com.protocoderspoint.androidokhttp;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.squareup.picasso.Picasso;

import org.jetbrains.annotations.NotNull;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {

    
    String myResponse;
    ListView lv;

    ArrayList<HashMap<String,String>> arrayList;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);
        arrayList=new ArrayList<>();
        lv = (ListView)findViewById(R.id.listview);



        OkHttpClient client = new OkHttpClient();
        String url = "https://protocoderspoint.com/jsondata/superheros.json";

        Request request = new Request.Builder()
                .url(url)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                if(response.isSuccessful())
                {

                    myResponse = response.body().string();
                    MainActivity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {


                            try {
                                JSONObject reader = new JSONObject(myResponse);
                                JSONArray superheros = reader.getJSONArray("superheros"); // get the whole json array list

                                System.out.println("json size is : "+superheros.length());

                                for(int i = 0;i<superheros.length();i++)
                                {
                                    JSONObject hero = superheros.getJSONObject(i);
                                    String name = hero.getString("name");
                                    String power = hero.getString("power");


                                    System.out.println(i+" Name: "+name +" Power : "+power);

                                    HashMap<String,String> data = new HashMap<>();

                                    data.put("name",name);
                                    data.put("power",power);


                                    arrayList.add(data);


                                    ListAdapter adapter = new SimpleAdapter(MainActivity.this,arrayList,R.layout.listview_layout
                                    ,new String[]{"name","power"},new int[]{R.id.name,R.id.power});

                                    lv.setAdapter(adapter);
                                }

                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    });
                }
            }
        });
    }
}

Brief detail about above source code

As we get Response using okHttp android library,

Then we are parsing  the data using JSON Parser

ArrayList HashMap as a String data

ArrayList<HashMap<String,String>> arrayList;

arrayList=new ArrayList<>();

arraylist will store all the data individually

String myResponse

myResponse = response.body().string();

Here is where we will hold the response.body() received from server API.

Get the JSONObject and JSONArray

JSONObject reader = new JSONObject(myResponse);
JSONArray superheros = reader.getJSONArray("superheros");

Then, Here we gonna trace the json data using JSONArray

looping through all the individual data

for(int i = 0;i<superheros.length();i++)
                                {
                                    JSONObject hero = superheros.getJSONObject(i);
                                    String name = hero.getString("name");
                                    String power = hero.getString("power");


                                    System.out.println(i+" Name: "+name +" Power : "+power);

                                    HashMap<String,String> data = new HashMap<>();

                                    data.put("name",name);
                                    data.put("power",power);


                                    arrayList.add(data);


                                    ListAdapter adapter = new SimpleAdapter(MainActivity.this,arrayList,R.layout.listview_layout
                                    ,new String[]{"name","power"},new int[]{R.id.name,R.id.power});

                                    lv.setAdapter(adapter);
                                }
Download from Google Drive

Guys, is you face any kind of problem, then feel free to contact_me

Http Request using OkHttp android library – Part 1

1

Hi Guys, Welcome to Proto Coders Point, In this Android Tutorial we gonna have a look on how to get response from server using OkHttp android library.

Note: This Android tutorial is kept simple for http request with okhttp library,

This is PART 1 – Here we will just fetch the data from server which is in json format and show data in Android TextView

Final Result of PART 1

okhttp android library screenshot example

What is OkHttp Library?

HTTP is the latest way to network in application. Now a days all data such as text,images or media are been exchange using HTTP CALLS.

Using OKHTTP will make our application stuff load content faster and saves lots of bandwidth.

Okhttp android library makes it simple to make any asynchronous HTTP request.

Using okhttp is quite very simple to get request/response API, It Supports both synchronous and asynchronous callls with callbacks.

Adding the library in our android project

implementation("com.squareup.okhttp3:okhttp:4.4.0")  // add this line in gradle.build(app level)

Check out the latest version of okhttp library in official website 

Internet permission

as we are making network called to fetch data from server we need to assign INTERNET permission

<uses-permission android:name="android.permission.INTERNET"/>

So to so open AndroidManifest.xml file and the <user-permissioon> Internet.

Snippet code to GET data from URL

OkHttpClient client = new OkHttpClient();  
        String url = "your api link here";

        Request request = new Request.Builder()
                .url(url)   //request for url by passing url
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                if(response.isSuccessful())
                {
                   // task after data is received 
                }
            }
        });

OkHttp will perform best when simple OkHttpClient instance is been created and reused it  in program when every needed to make HTTP Calls, This is best each client is given to hold its own  connection so this makes the task smooth, fast and easy to load data from server side.

Complete Source Code to make Http Request using OkHttp android library – Part 1

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textview1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

This have only one widget(textview) where are gonna show the date response for server

MainActivity.java

package com.protocoderspoint.androidokhttp;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.TextView;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {

    TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        textView = (TextView)findViewById(R.id.textview1);

        OkHttpClient client = new OkHttpClient();
        String url = "https://protocoderspoint.com/jsondata/superheros.json";

        Request request = new Request.Builder()
                .url(url)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                if(response.isSuccessful())
                {
                    final String myResponse = response.body().string();
                    MainActivity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            textView.setText(myResponse);                // runOnUiThread is used because A Thread is current used by OkHttp Thread
                        }
                    });
                }
            }
        });
    }
}

 

 

 

Flutter http example – fetching data from internet json & display in listview

3
Flutter http example display dynamic data in listview

Hi Guys, Welcome to Proto Coders Point, In this Flutter Tutorial we gonna use the HTTP flutter library to Fetch data from the Internet which is in JSON format, and display the data in Flutter ListView builder with ListTile widget.

let’s begin by adding HTTP dart package into our project

Final Result of this Flutter Demo Application

flutter http example dynamic data in listview

Http Dart Package

Step 1 : Add http dependencies

Open pubspec.yaml file and add the below lines of code

dependencies:
  http: ^0.12.0+4   //add this line

Once you add the dependencie hit Packages Get , what this does is that get all the packages from interent and store them in you flutter project.

Step 2 : Import the http dart package

import 'package:http/http.dart';

You need to import the http.dart file under you project file where you want to make use of it.

All set now let’s check how to get data from server or any REST API

I have created a dummy JSON DATA on my server which we are using in this flutter http example to fetch json data.

Link of my JSON DATA or API : https://protocoderspoint.com/jsondata/superheros.json

my json API data for flutter http request get

How to use http library in flutter?

void getData() async {

    http.Response response =  await http.get(Uri.parse("https://protocoderspoint.com/jsondata/superheros.json"));

    //if response is 200 : success that store 
    if (response.statusCode == 200) {
      String  data = response.body; //store response as string

      setState(() {
        superheros_length = jsonDecode(data)['superheros']; //get all the data from json superheros

        print(superheros_length.length); // just printed length of data
      });


      var venam = jsonDecode(data)['superheros'][4]['power']; // get data from particular index

      print(venam);
    } else {
      print(response.statusCode);
    }
  }

How to Show/Display data from Server in Flutter listView?

To show Dynamic contents in flutter listview we make use of listview.builder() widget.

ListView.builder is commonly been used to construct a children’s widgets as much as required depending on the dynamic data you receive from server or API calls.

ListView.builder comes with parameters like

itemCount : describes how many itemBuilder ( widget ) must be created

ListView.builder(
        itemCount: superheros_length == null ? 0 : superheros_length.length,
        itemBuilder: (BuildContext context, int index) {
          return Card(
            child: ListTile(
              leading: Image.network(
                jsonDecode(data)['superheros'][index]['url'],
                fit: BoxFit.fill,
                width: 100,
                height: 500,
                alignment: Alignment.center,
              ),
              title: Text(jsonDecode(data)['superheros'][index]['name']),
              subtitle: Text(jsonDecode(data)['superheros'][index]['power']),
            ),
          );
        },
      ),

itemBuilder : will create as many as widgets specified in itemCount

For Example : itemCount : 5  then itemBuilder will simply create 5 widget on the screen

This above Snippet code will generate Card with child: as ListTile Widget.

Flutter http example – fetching data from internet json and display in listview

Complete Source code to fetch data from server using Flutter HTTP

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  String data;
  var superheros_length;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getData();
  }

  void getData() async {
    http.Response response =
        await http.get(Uri.parse("https://protocoderspoint.com/jsondata/superheros.json"));

    if (response.statusCode == 200) {
      data = response.body; //store response as string

      setState(() {
        superheros_length = jsonDecode(
            data)['superheros']; //get all the data from json string superheros

        print(superheros_length.length); // just printed length of data
      });

      var venam = jsonDecode(data)['superheros'][4]['url'];

      print(venam);
    } else {
      print(response.statusCode);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Flutter Http Example"),
      ),
      body: ListView.builder(
        itemCount: superheros_length == null ? 0 : superheros_length.length,
        itemBuilder: (BuildContext context, int index) {
          return Card(
            child: ListTile(
              leading: Image.network(
                jsonDecode(data)['superheros'][index]['url'],
                fit: BoxFit.fill,
                width: 100,
                height: 500,
                alignment: Alignment.center,
              ),
              title: Text(jsonDecode(data)['superheros'][index]['name']),
              subtitle: Text(jsonDecode(data)['superheros'][index]['power']),
            ),
          );
        },
      ),
    );
  }
}

 

Recommended Articles

listwheelscrollview3D ListView in flutter

Integration of Google Maps in Flutter with Example using a plugin

1

Hi Guys, Welcome to Proto Coders Point, In this Flutter Tutorial we gonna integrate Flutter Google Maps in our Flutter Project using a Plugin.

So to add google maps in your flutter project, Google API is needed.

DEMO

google maps flutter example in gif

Step 1: How to get Google Map API key?

To get API key go to the link https://cloud.google.com/maps-platform/ Create a new Google Project under your console.

Follow the Screenshot Steps to get API

step 1 to get API key credentials

create new credential api key

how to get google api key

Then now you have API key with you, keep a note of it.

Step 2 : adding google maps flutter dependencies

Do Follow this link the official site to get latest version here

Open pubspec.yaml file and app the plugin library dependencies file.

dependencies:
  google_maps_flutter: ^0.5.25 // add this line

Step 3: Import the google map flutter library

After you have added the required dependencies now you need to import the library whereever  you need to implement google maps in flutter app.

import 'package:google_maps_flutter/google_maps_flutter.dart';

Step 4 : Specifying the Google API key in AndroidManifest.xml ( ANDROID )

open AndroidManifest.xml file and add the <meta-data> tag inside <application> tag

<manifest ...
  <application>

    <meta-data android:name="com.google.android.geo.API_KEY"
               android:value="YOUR KEY HERE"/>                  // add this line and replace with you API KEY

  </application>
</manifest>

Step 5: Specifying API key in AppDelegate.swift ( for iOS)

in iOS you need to Specify Application delegates  to make use of google maps services in  IOS

To do so navigate ios/Runner/AppDelegate.swift

import UIKit
import Flutter
import GoogleMaps   // add this line 

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
    GMSServices.provideAPIKey("YOUR KEY HERE")      // add this line replace  with your API KEY
    GeneratedPluginRegistrant.register(with: self)
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
}

 

Snippet code of GoogleMaps widget in flutter

GoogleMap(
      mapType: MapType.normal,
      initialCameraPosition:
          CameraPosition(target: LatLng(15.841461, 74.512202), zoom: 18),
      onMapCreated: (GoogleMapController controller) {
        _controller.complete(controller);
      },
      markers: {belgaum},
    ),

mapType: Specify which kind of map interface do you want to load.

  • normal.
  • satellite.
  •  hybrid.
  • terrain.

MapType in flutter google maps widget

initialCameraPosition: This will load the map with initial camera position may be currect location of the users.

onMapCreated: this will create a map with complete controls to the map you can zoom in, zoom out, go to other location in the map and many things under your controls.

Google Marker

Marker belgaum = Marker(
  markerId: MarkerId("Belgaum"),
  position: LatLng(15.841461, 74.512202),
  infoWindow: InfoWindow(title: "Belgaum"),
  icon: BitmapDescriptor.defaultMarkerWithHue(BitmapDescriptor.hueRose),
);

The Marker will keep a marker on the position you have or any be the destination point you want to travel to.

Flutter google maps  Complete Source Code with example

Copy paste the below source code in main.dart file

NOTE: Don’t forget to specify the API KEY, else the google maps will not work/load.

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';

void main() => runApp(MyApp());
Completer<GoogleMapController> _controller = Completer();

class MyApp extends StatelessWidget {
  // This widget is the root of your application.

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Google Maps in Flutter Example"),
      ),
      body: Stack(
        children: <Widget>[_googleMaps(context)],
      ),
      floatingActionButton: FloatingActionButton.extended(
        onPressed: _goToNextLocation,
        label: Text('To the Next Location'),
        icon: Icon(Icons.directions_boat),
      ),
    );
  }
}

Widget _googleMaps(BuildContext context) {
  return Container(
    height: MediaQuery.of(context).size.height,
    width: MediaQuery.of(context).size.width,
    child: GoogleMap(
      mapType: MapType.terrain,
      initialCameraPosition:
          CameraPosition(target: LatLng(15.841461, 74.512202), zoom: 18),
      onMapCreated: (GoogleMapController controller) {
        _controller.complete(controller);
      },
      markers: {belgaum},
    ),
  );
}

Marker belgaum = Marker(
  markerId: MarkerId("Belgaum"),
  position: LatLng(15.841461, 74.512202),
  infoWindow: InfoWindow(title: "Belgaum"),
  icon: BitmapDescriptor.defaultMarkerWithHue(BitmapDescriptor.hueRose),
);

Future<void> _goToNextLocation() async {
  final GoogleMapController controller = await _controller.future;
  controller.animateCamera(
    CameraUpdate.newCameraPosition(
      CameraPosition(
          target: LatLng(37.43296265331129, -122.08832357078792),
          zoom: 19.151926040649414,
          tilt: 59.440717697143555,
          bearing: 192.8334901395799),
    ),
  );
}

 

How to Make Email Validation in Flutter – Using Email Validator Library

0
Flutter Email Validation library
Hi Guys, Welcome to Proto Coders Point,  In this Flutter Tutorial we will integrate Flutter library called Email Validator to validate email address.

Email Validation

Usually Email Validation is done, by a String value that contains alphabets, @ symbols and a .(dot) symbol For Example: contact@protocoderspoint.com, This email address contains all the characters required to be a perfect/valid email address.

Flutter Email Validation Library

Flutter Comes with awesome and easy to use flutter Library/Plugins. This Email validation flutter library is pre defined class that validated email addresses. You just need to call its class. This plugin is very easy to use and understand. Visit official site to learn more here Let’s start adding the library in our Flutter Project.

Adding Dependencies in our project

Open Pubspec.yaml and add the dependencies
dependencies:
  email_validator: ^1.0.4 // add this line

Import the email validator dart class

you need to import the email_validator.dart file, where you want to make use validator library. In my case i have imported it in main.dart file
import 'package:email_validator/email_validator.dart';
And their you go now you can use the library.

Snippet Code Example how to use it

    const String email = 'contact@protocoderspoint.com';
    final bool isValid = EmailValidator.validate(email);

    print('Email is valid? ' + (isValid ? 'yes' : 'no'));
The above code is snippet code, Their is a string that holds email address, a boolen type variable that stored true or false based on email address, is the email is valid it will store true else false. (isValid ? ‘yes’ : ‘no’) :  is similar to if else statement.

Complete code on Email Validation in flutter

In my flutter project i have 2 dart files. main.dart is with TextFormField() where we will check if email is valid, if entered email is valid that the user will be navigated to page2.dart main.dart Copy paste the below code in main.dart
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:email_validator/email_validator.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'page2.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.yellow,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final _emailcontroller = TextEditingController();
  bool isvalid = false;

  @override
  Widget build(BuildContext context) {
    double width = MediaQuery.of(context).size.width;
    return Scaffold(
      appBar: AppBar(
        title: Text("Email Validate Example"),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Center(
          child: Column(
            children: <Widget>[
              Text(
                "Example on Email Validation",
                style: TextStyle(
                    fontSize: 20,
                    fontWeight: FontWeight.bold,
                    fontStyle: FontStyle.italic),
              ),
              Container(
                height: 10,
              ),
              TextFormField(
                controller: _emailcontroller,
                decoration: InputDecoration(
                    labelText: "Email",
                    labelStyle: TextStyle(color: Colors.blue),
                    focusedBorder: OutlineInputBorder(
                        borderSide: BorderSide(color: Colors.red),
                        borderRadius: BorderRadius.circular(10.0)),
                    enabledBorder: OutlineInputBorder(
                        borderSide: BorderSide(color: Colors.red),
                        borderRadius: BorderRadius.circular(10.0))),
              ),
              SizedBox(
                height: 10,
              ),
              RaisedButton(
                onPressed: () {
                  isvalid = EmailValidator.validate(_emailcontroller.text);
                  if (isvalid) {
                    Navigator.push(context,
                        MaterialPageRoute(builder: (context) => Page2()));
                  } else {
                    Fluttertoast.showToast(
                        msg: "Please Enter a valid Email",
                        toastLength: Toast.LENGTH_SHORT,
                        gravity: ToastGravity.BOTTOM,
                        timeInSecForIos: 1,
                        backgroundColor: Colors.red,
                        textColor: Colors.white,
                        fontSize: 16.0);
                  }
                },
                child: Container(
                  width: width * 0.5,
                  child: Center(
                    child: Text(
                      "Submit",
                      style: TextStyle(color: Colors.white),
                    ),
                  ),
                ),
                color: Colors.blue,
              ),
            ],
          ),
        ),
      ),
    );
  }
}
page2.dart Create a new dart page in lib folder of your flutter project and add below code. the below code is simply a UI where we show a Text.
import 'package:flutter/material.dart';

class Page2 extends StatefulWidget {
  @override
  _Page2State createState() => _Page2State();
}

class _Page2State extends State<Page2> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Email Validator Flutter plugin"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text("Email Address is validate"),
          ],
        ),
      ),
    );
  }
}
Check out Similar Articles on Validation Flutter Password Validation Flutter Form Validation Flutter Email Validation using plugin Flutter Email Regex Pattern