Home Blog Page 75

Flutter Form Validation- Email validate, confirm Password validation

0
flutter form validation email and password confirm
flutter form validation email and password confirm

Hi Guys, Welcome to Proto Coders Point, In this Flutter Tutorial we will check how to create forms in flutter with validation such as empty TextField, Email Validation, and password and confirm password validation in flutter

So let’s begin

Steps for form validation

  1. Create Form with a GlobalKey<FormState>.
  2. Add some TextFormField with validation that required.
  3. Create a button where you check for flutter form validation and submit it.

Step 1: Form Creation and assigning it a GlobalKey with FormState

First make use of Form Widget, This will work as a group & help you in managing validating multiple flutter forms textfield easily.
Then, after creating a form in flutter, provide it with GlobalKey<FormState>, It will help you  in allowing validation to form in proper order & very easily.

As show in below Snippet flutter code

final _formKey = GlobalKey<FormState>();

@override
  Widget build(BuildContext context) {
    // Build a Form widget using the _formKey created above.
    return Form(
      key: _formKey,    
      child: Column(
        children: <Widget>[
              // Add TextFormFields and RaisedButton here.
        ]
     )
    );
  }

Here i have created a globalkey as formState then in widget Tree, I have made use of Form Widget and assigned key: as _formKey, and form has child as Column so that we can create TextFormField for Flutter Form Validation.

Step 2: Adding TextFormField with Validation email, password confirm

TextFormField widget comes from Material design & it can also display validation error, whenever any user do not fullfill TextFormField Requirement,
This we can do by applying Validation Rules to particular flutter Textfield by providing validation properties rules to it.

If user enter any invalid input, then Validator function in flutter will detect it & return a appropriate error message at the bottom of TextField.

TextFormField(
  // The validator receives the text that the user has entered.
  validator: (value) {
    if (value.isEmpty) {
      return 'Please enter some text';
    }
    return null;
  },
);

If user submit the form without any data then validator will take care by showing proper text message to user, as shown in below screenshot.

flutter form validation using global formstate

Step 3: OnButton Pressed Check for Form Validation

So, Now as you have designed flutter form with TextFormField with validation, now simple create a button(should be inside the Form Widget tag), using which the user can submit the form filled with information in it.

When a user attempt to submit the form onPressed, we will check if flutetr form field by user is as per required validation, Then if the form is valid then send all the data info to database server to be saved, else if the form is invalidthen show a proper error message to the user under the flutter textfield where validation is not authorized.

RaisedButton(
  onPressed: () {
    // Validate returns true if the form is valid, otherwise false.
    if (_formKey.currentState.validate()) {
      // If the form is valid, display a snackbar. In the real world,
      // you'd often call a server or save the information in a database.

      Scaffold
          .of(context)
          .showSnackBar(SnackBar(content: Text('Processing Data')));
    }
  },
  child: Text('Submit'),
);

We are using GlobalKey formState under Form so, Form Validation will automatically detect where uses validation has failed.

Video Tutorial

Complete Source Code of Form Validation in Flutter

UI Design

flutter form validation email confirm password

Project Structure

Here InputDeco_design.dart file is an decoration of TextFormField, As you can see in UI design TextField has border and radius.

Source Codes


main.dart

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_form_validator/FormPage.dart';
import 'package:flutter_form_validator/InputDeco_design.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',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: FormPage(),
    );
  }
}



InputDeco_design.dart

import 'package:flutter/material.dart';

  InputDecoration buildInputDecoration(IconData icons,String hinttext) {
  return InputDecoration(
    hintText: hinttext,
    prefixIcon: Icon(icons),
    focusedBorder: OutlineInputBorder(
      borderRadius: BorderRadius.circular(25.0),
      borderSide: BorderSide(
          color: Colors.green,
          width: 1.5
      ),
    ),
    border: OutlineInputBorder(
      borderRadius: BorderRadius.circular(25.0),
      borderSide: BorderSide(
        color: Colors.blue,
        width: 1.5,
      ),
    ),
    enabledBorder:OutlineInputBorder(
      borderRadius: BorderRadius.circular(25.0),
      borderSide: BorderSide(
        color: Colors.blue,
        width: 1.5,
      ),
    ),
  );
}

FormPage.dart

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

class FormPage extends StatefulWidget {
  @override
  _FormPageState createState() => _FormPageState();
}

class _FormPageState extends State<FormPage> {

  String name,email,phone;

  //TextController to read text entered in text field
  TextEditingController password = TextEditingController();
  TextEditingController confirmpassword = TextEditingController();

  final GlobalKey<FormState> _formkey = GlobalKey<FormState>();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: SingleChildScrollView(
          child: Form(
            key: _formkey,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                CircleAvatar(
                  radius: 70,
                  child: Image.network("https://protocoderspoint.com/wp-content/uploads/2020/10/PROTO-CODERS-POINT-LOGO-water-mark-.png"),
                ),
                SizedBox(
                  height: 15,
                ),
                Padding(
                  padding: const EdgeInsets.only(bottom:15,left: 10,right: 10),
                  child: TextFormField(
                    keyboardType: TextInputType.text,
                    decoration: buildInputDecoration(Icons.person,"Full Name"),
                    validator: (String value){
                      if(value.isEmpty)
                      {
                        return 'Please Enter Name';
                      }
                      return null;
                    },
                    onSaved: (String value){
                      name = value;
                    },
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.only(bottom: 15,left: 10,right: 10),
                  child: TextFormField(
                    keyboardType: TextInputType.text,
                    decoration:buildInputDecoration(Icons.email,"Email"),
                    validator: (String value){
                      if(value.isEmpty)
                      {
                        return 'Please a Enter';
                      }
                      if(!RegExp("^[a-zA-Z0-9+_.-]+@[a-zA-Z0-9.-]+.[a-z]").hasMatch(value)){
                        return 'Please a valid Email';
                      }
                      return null;
                    },
                    onSaved: (String value){
                      email = value;
                    },
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.only(bottom: 15,left: 10,right: 10),
                  child: TextFormField(
                    keyboardType: TextInputType.number,
                    decoration:buildInputDecoration(Icons.phone,"Phone No"),
                    validator: (String value){
                      if(value.isEmpty)
                      {
                        return 'Please enter phone no ';
                      }
                      return null;
                    },
                    onSaved: (String value){
                      phone = value;
                    },
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.only(bottom: 15,left: 10,right: 10),
                  child: TextFormField(
                    controller: password,
                    keyboardType: TextInputType.text,
                    decoration:buildInputDecoration(Icons.lock,"Password"),
                    validator: (String value){
                      if(value.isEmpty)
                      {
                        return 'Please a Enter Password';
                      }
                      return null;
                    },

                  ),
                ),
                Padding(
                  padding: const EdgeInsets.only(bottom: 15,left: 10,right: 10),
                  child: TextFormField(
                    controller: confirmpassword,
                    obscureText: true,
                    keyboardType: TextInputType.text,
                    decoration:buildInputDecoration(Icons.lock,"Confirm Password"),
                    validator: (String value){
                      if(value.isEmpty)
                      {
                        return 'Please re-enter password';
                      }
                      print(password.text);

                      print(confirmpassword.text);

                      if(password.text!=confirmpassword.text){
                        return "Password does not match";
                      }

                      return null;
                    },

                  ),
                ),

                SizedBox(
                  width: 200,
                  height: 50,
                  child: RaisedButton(
                    color: Colors.redAccent,
                    onPressed: (){

                      if(_formkey.currentState.validate())
                      {
                        print("successful");

                        return;
                      }else{
                        print("UnSuccessfull");
                      }
                    },
                    shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(50.0),
                        side: BorderSide(color: Colors.blue,width: 2)
                    ),
                    textColor:Colors.white,child: Text("Submit"),

                  ),
                )
              ],
            ),
          ),
        ),
      ),
    );
  }
}

Output

Flutter Form Email Validation

flutter validation email

Flutter form confirm password –
password and confirm password validation must match

flutter password validation and confirm password validation must match

Download Source Code from GitHub  Link: https://github.com/RajatPalankar8/flutter_form_validation.git 

Recommended Articles

flutter email validation

password validation regex – Android

Flutter GetX Route Management – Getx Navigation in Flutter

3
Flutter getx routes management example

Hi Guys, Welcome to Proto Coders Point, In this Flutter tutorial we will discuss Flutter Getx Route Management, getx routing Made easy with this awesome library.

What is Flutter GetX?

The GetX library in flutter is a very extra lightweight plugin & a powerful package that will help flutter developers to build apps much faster.

Using GetX we can easily switch between screens, show snack bar, show dialog, and bottom sheet that too without passing any context.

Then, it combines high-performance state management, intelligent dependency injection & route management that too quickly.

learn more:  Introduction to getx library

Learn more in detail about this library from the official site

https://pub.dev/packages/get

Video Tutorial

 

Installation of GetX plugin

Create a new Flutter Project and under your project, you will see pubspec.yaml file open it: add this package under the dependencies section

dependencies:
  get: ^3.13.2   #check official site of latest version

import it and use it wherever required

import 'package:get/get.dart';

Ok, So now we are done with the basic requirement,

In this tutorial, we will check only GetX Route Management, So let’s begin

Flutter Getx Routes Management

If you want to create a snack bar, dialogs, bottom sheet, and a complete routers of your flutter then, GETX is excellent to make use of:

Note: To use getx  you need to wrap the root of your flutter project with GetMaterialApp instead of using simply MaterialApp

snippet code

GetMaterialApp(
      title: 'Flutter Demo',
      debugShowCheckedModeBanner: false,
      home: HomePage(),
      theme: ThemeData(

        primarySwatch: Colors.blue,

        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
    );

As you can see in the above snippet code I have just wrapped the root node with GetMaterialApp so that I can use getx properties anywhere in the application.

Properties of Getx Routes

Navigate to a new screen

Get.to(nextScreen());

To go to the next Screen & no option  to go back to the previous screen ( you can use this in SplashScreen, Registration Screen or Login Screen )

Get.off(nextScreen());

Then, to go to the next screen but you want to forget all the previous routes that you traveled then use this:

Get.offAll(NextScreen());

Using Flutter Routes name

Snippet Code

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      title: 'Flutter Demo',
      debugShowCheckedModeBanner: false,

      // starting point from where app should begin
      initialRoute: '/',

      //when initial Route is given no need to add home widget for initial start point of app
      //full app route structure

      routes: {
        '/':(context)=> MyHomePage(),
        '/login':(context)=>LoginPage(),
        '/reg':(context)=>Registration(),
        '/dashboard':(context)=>Dashboard()
      },

      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
    );
  }
}

As you can see in the above code,
I have created some routes to other pages in your app,
So now will be check Getx properties that can help you in Navigation using Routes Names.

Navigation to named routes

Get.toNamed('/login');   // this will take you to login page

Navigation to named Routes but forget/removing all previously traveled routes

Get.offAllNamed('/dashboard');

Goes to the next page, and then removes the previous one.

Get.offAndToNamed('/dashboard');

Demo Project- just to Demonstrate Route Management using GetX

This is the project structure
Project Structure getx flutterNote: This is just a dummy project with a simple login registration screen(without any actual functionality) just to show Route management in flutter using GetX.

Here are the Codes

main.dart

import 'package:flutter/material.dart';
import 'package:flutter_getx_routes/Dashboard.dart';
import 'package:flutter_getx_routes/LoginPage.dart';
import 'package:flutter_getx_routes/MyHomePage.dart';
import 'package:flutter_getx_routes/Registration.dart';
import 'package:get/get.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      title: 'Flutter Demo',
      debugShowCheckedModeBanner: false,
      // starting point from where app should begin
      initialRoute: '/',
      //when initial Route is given no need to add home widget for initial start point of app
      //full app route structure

      routes: {
        '/':(context)=> MyHomePage(),
        '/login':(context)=>LoginPage(),
        '/reg':(context)=>Registration(),
        '/dashboard':(context)=>Dashboard()
      },

      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
    );
  }
}



MyHomePage.dart

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

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

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            FlatButton(onPressed: (){
                  Get.toNamed('/login');
            }, child: Text("GO TO LOGIN PAGE ",style: TextStyle(color: Colors.white),),color: Colors.blue,)
          ],
        ),
      ),
    );
  }
}

 


Registration.dart

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

class Registration extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        child: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text("Registration page",style: TextStyle(fontSize: 25),),
              //// textField only for Simple UI, there is not event happening in it
              Padding(
                padding: const EdgeInsets.only(left: 25,right: 25),
                child: TextField(
                    decoration:  InputDecoration(
                      hintText: "User Name",
                    )
                ),
              ),Padding(
                padding: const EdgeInsets.only(left: 25,right: 25),
                child: TextField(
                    decoration:  InputDecoration(
                      hintText: "Password",
                    )
                ),
              ),
              SizedBox(height: 20,),
              FlatButton(onPressed: () {

                // after registration successful remove all the previous screen visited and goto dashboard page
                Get.offAllNamed('/dashboard');

              } ,
             child: Text("Register",style: TextStyle(color: Colors.white),),color: Colors.blue,),
              SizedBox(height: 10,),

              //// Go to Login page from registration if already registered  using getx toNamed properties

              GestureDetector(onTap: ()=> Get.offAllNamed('/login'),child: Text("Already Done ? Login Now ")),
            ],
          ),
        ),
      ),
    );
  }
}

LoginPage.dart 

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

class LoginPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        child: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text("Login page",style: TextStyle(fontSize: 25),),
              //// textField only for Simple UI, there is not event happening in it
              Padding(
                padding: const EdgeInsets.only(left: 25,right: 25),
                child: TextField(
                    decoration:  InputDecoration(
                      hintText: "User Name",
                    )
                ),
              ),Padding(
                padding: const EdgeInsets.only(left: 25,right: 25),
                child: TextField(
                    decoration:  InputDecoration(
                      hintText: "Password",
                    )
                ),
              ),
              SizedBox(height: 20,),
              FlatButton(onPressed: () {

                // after Login successful remove all the previous screen visited and goto dashboard page
                Get.offAllNamed('/dashboard');

              } , child: Text("Login",style: TextStyle(color: Colors.white),),color: Colors.blue,),
              SizedBox(height: 10,),

              //// Go to Registration page is new user using getx toNamed properties
              GestureDetector(onTap: ()=> Get.toNamed('/reg'),child: Text("New User? Register Now")),
            ],
          ),
        ),
      ),
    );
  }
}

Dashboard.dart

import 'package:flutter/material.dart';

class Dashboard extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        child: Center(
          child: Text("Dashboard page"),
        ),
      ),
    );
  }
}

Output

flutter getx route management example output

Recommended Articles on Flutter Getx

Introduction to getX Flutter example

Flutter State management using GetX

Flutter State Management using GetX – Firebase Firestore Cloud Example

1
Flutter getx state management with firebase firestore example
Flutter getx state management with firebase firestore example

Hi Guys, Welcome to Proto Coders Point, In this Flutter Tutorial we gonna implement Flutter State Management using the GetX plugin (Flutter Made Easy) & also an example to reflect the firebase firestore data change using GetX & StreamBuilder.

What is Flutter GetX?

The GetX library in flutter is a very extra lightweight plugin & a powerful package that will help flutter developers to build apps much faster.

Using GetX we can easily switch between screens, show snack bar, show dialog and bottom sheet that too without passing any context.

Then, it combines high-performance state management, intelligent dependency injection & route management that to quickly.

learn more:  Introduction to getx library


Video Tutorial

Let’s begin

Required Flutter Dependencies for the tutorial

under your project open pubspec.yaml file and under dependencies section add them.

dependencies:
  get:   # getx plugin

  #firebase
  cloud_firestore: ^0.14.1+3 #to make use of firebase classes and methods

Here I have made use of 2 dependencies

  1. get:  to add getx package to our flutter project, Using getx, flutter app development become much faster, you can easily achieve task such as showing snack bar, dialog and many more like state management and route management. learn more: https://pub.dev/packages/get
  2. cloud_firestore: To play with Firebase cloud firestore data, Cloud Firestore is a flexible, NoSQL cloud database to store data.  learn more: https://pub.dev/packages/cloud_firestore

Flutter State Management using GetX – Example 1

This Example 1 – will be on Normal/Static data to demonstrate State Management using GetX.

1st Step: Create a new Flutter Project

2nd Step: Add Get dependencies

dependencies:
  get:

Add the dependencies and hit the pub get button.


3rd Step: Create a new Dart file in the lib

In your lib directory create a new dart file and name it as “CounterState.dart”

Then the below code has

A variable count with an initial value of 0 which is kept in observable
observable means any changes in this variable will be reflected to its consumer.

Then, I have an increment() function, when called will increase count by +1.

import 'dart:async';
import 'package:get/get.dart';

class CounterState extends GetxController{

  var count = 0.obs;

  increment()=> count++;
}

4th Step: Under main.dart file

main.dart

In the below code I have added a comment refer it

As you can see below code
First of all, I have created an instance of a class CounterState, then I am using Instance Object to get data of the class variable (count) and to call increment to increment the count value by +1.

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_getx_demo/CounterState.dart';
import 'package:get/get.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 GetMaterialApp(
      title: 'Flutter Demo',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(

        primarySwatch: Colors.blue,

        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(),
    );
  }
}

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

class _MyHomePageState extends State<MyHomePage> {

  final CounterState counterState = Get.put(CounterState());  // create instance of a class.

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Center(
            child: Obx(()=>Text("Counter Value is : ${counterState.count} ") ), //get count variable value
          ),
          FlatButton(onPressed: (){

            Get.to(Page2());  //getx to navigate

          }, child: Text("GO TO PAGE 2"),color: Colors.blue,),  
        ],
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
               counterState.increment();  //on button press call increment function
        },
        child: Icon(Icons.add),
      ),
    );
  }
}




5th Step: Create a new dart Page

Create a new Dart file by the name “Page2.dart”.

Here first create an Instance of a class and using Get we can find the updated value of the data present in that CounterState class.

I mean to say the incremented value on both the page will be same.

import 'package:flutter/material.dart';
import 'package:flutter_getx_demo/CounterInstance.dart';
import 'package:get/get.dart';

class Page2 extends StatelessWidget {

  final CounterInstance counterInstance = Get.find();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Text("${counterInstance.count}",
                 style: TextStyle(fontSize: 25),
                 ),
      ),
    );
  }
}

Watch this video tutorial for the basic of Flutter GetX 

 



Flutter State Management using GetX – Firebase firestore Example 2

This is Example 2 – Will be dynamic state management using GetX controller and StreamBuilder.

First of all, you need to connect your flutter project with the firebase console

1st Step: Create a new project in the firebase console

adding flutter project to firebase console

Then, add the app
Select Android
(Sorry, I don’t have iPhone or MAC BOOK to show to iOS steps)

firebase android package name add project

Find Android package name under AndroidManifest.xml file
Flutter Project > android > app > AndroidManifest.xml

Then Firebase will give you a googleservices.json file that you need to add under
Flutter Project > android > app 

adding google services

then, you need to add some firebase dependencies and classpath

Project-level build.gradle (<project>/build.gradle):

buildscript {
  repositories {
    // Check that you have the following line (if not, add it):
    google()  // Google's Maven repository
  }
  dependencies {
    ...
    // Add this line
    classpath 'com.google.gms:google-services:4.3.4'
  }
}

allprojects {
  ...
  repositories {
    // Check that you have the following line (if not, add it):
    google()  // Google's Maven repository
    ...
  }
}

App-level build.gradle (<project>/<app-module>/build.gradle):

apply plugin: 'com.android.application'
// Add this line
apply plugin: 'com.google.gms.google-services'    //add this line

dependencies {
  // Import the Firebase BoM
  implementation platform('com.google.firebase:firebase-bom:25.12.0')   //add this line

  implementation 'com.google.firebase:firebase-analytics'    //add this line


}

then, you are done, now just run your app on your physical device to check if your app is connected to the firebase server.
Firebase Console will show you a message, saying you are successfully connected.


2nd Step: Add Required Dependencies

dependencies:
  get:     #for GETX plugin
  cloud_firestore: ^0.14.1+3    #to get data from Firestore cloud

add this to both dependencies and hit the pub get button.


3rd Step: Let’s Create firestore database collection

Go to Firebase Console, and open the recent project you are work on and then go to Cloud Firestore > here create a new Database,
and Enter the path/data collection as shown in the below screenshot

cloud firestore collection data

this will be the path where we will store the count variable data.

4th Step: Coding – using GetX and StreamBuilder

CounterState.dart

Here Stream is used to keeping a look at data snapshot changes, Whenever any data is been changed in the server, automatically the consumer of that data will get updated Stream to listen, StreamController and StreamBuilder.

 

import 'dart:async';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:get/get.dart';

class CounterState extends GetxController{
  
  StreamController<int> streamController   = StreamController<int>();

  // the path from where our data will be fetched and displayed to used 
  Stream<DocumentSnapshot> doc =      Firestore.instance.collection("data").document("counterState").snapshots();
  
  void StartStream(){
      doc.listen((event) {
         // here count is a field name in firestore database 
        streamController.sink.add(event.data()['count']);
      });
  }
  
  @override
  FutureOr onClose() {
    streamController.close();
  }
}

main.dart

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_getx_demo/CounterState.dart';
import 'package:get/get.dart';
import 'Page2.dart';
void main() async{
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();    // initializedApp with Firebase
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
   // wrap full app with GetMaterialApp so that GetX properties can be used
    return GetMaterialApp(
      title: 'Flutter Demo',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(

        primarySwatch: Colors.blue,

        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(),
    );
  }
}

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

class _MyHomePageState extends State<MyHomePage> {

  int count ; // a variable that store data value available in server

  // create instance of a class using getX put properties
  final CounterState counterState = Get.put(CounterState());

  @override
  void initState() {
    super.initState();
    //start fetching data from firebase server
    counterState.StartStream();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
             // StreamBuilder that keep UI up to date 
             // in the sense when data is been changed is refected to app UI
            StreamBuilder(
                stream:  counterState.streamController.stream,
                builder: (BuildContext context,AsyncSnapshot<dynamic> snapshot){
                  count = snapshot.data;
                  return Text("Stream : $count ");
                }
            ),

            FlatButton(
              onPressed: (){
               // call function to add +1
              _Add_data();

              },color: Colors.blue,

              child: Text("Add +1 ",style: TextStyle(color: Colors.white),),
            ),
          ],
        ),
      ),
     
    );
  }

  void _Add_data() {
    // collection field where data should be updated
    Map<String,int> demodata = {
      "count":(count+1).toInt(),
    };

    //the document path where data much be updated
    DocumentReference  documentReference = Firestore.instance.collection("data").document("counterState");
    //
    documentReference.update(demodata);
  }

}



The explanation is been done in the above code in //comment  read them

Output

View post on imgur.com

Recommended post on Flutter GetX Library

Introduction to Flutter GetX

Flutter GetX Route Management

Firebase Authentication using Flutter GetX libraryVelocityX

Flutter Firebase Google Sign In method

Introduction to Flutter GetX | Development made easy with GetX Plugin

6
flutter getx

Hi Guys, Welcome to Proto Coders Point, In this Flutter Tutorial we gonna introduce you with best development plugin that makes flutter software development easy and fast i.e Flutter GetX.

This Tutorial Article will be just an Introducton to Flutter GetX Plugin & How to you can install it in your flutter project and basic of how to us getX.

Learn more about the Plugin from Offical Site in details https://pub.dev/packages/get

Video Tutorial 

What is Flutter GetX?

The GetX library in flutter is very extra light weight plugin & a powerful package that will help flutter developer to build apps much faster.

Using GetX we can easily switch between screens, show snackbar, show dialog and bottomsheet that too without passing any context.

Then, it combimes high performance state management, intelligent dependency injection & route management that to quickly.

Feature provided in Flutter GetX library

  1. State Management
  2. Route Management
  3. Dependency Management
  4. Validation & much more.

This are 3 very useful feature of GetX package that makes developer to build Android, iOS apps faster.

Note: Seperate Tutorial on the above feature of this plugin will be made very soon in upcoming Articles.

Installation of GetX Plugin

Add Get to your pubspec.yaml file of your flutter project:

dependencies:
  get: ^version

Import get where it is need:

import 'package:get/get.dart';

Then, to use getX you just you need to Change Root Widget MaterialApp with GetMaterialApp for Example See below Snippet Code

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(                  //LIKE THIS 
      title: 'Flutter Demo',
      theme: ThemeData(

        primarySwatch: Colors.blue,

        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(),
    );
  }
}

After Wraping as shown above you can easily use GetX method in child widgets.

Basic Snippet code of GetX library/ How to use GetX

Before we had to write long long code to make simple events in app for Example to more from one page to other page

Old Flutter Route Management code

Navigator.push(context, 
                MaterialPageRoute(
                              builder: (context)=>MyHomePage()
                              )
               );

In above code as you can see you need to write such a long code just to go to other screen. this can we done easily in 1 line using Getx syntax that too without passing context.

Using GetX to Navigate to Pages

//Easy Navigation
Get.to(Page2());

Route Management/Navigation using GetX is made easy using this Get X library, Just you need to do is on Button Press or any event occur call the above code.

Showing Snackbar & Dialog Box

Get.snackbar("Hi", "message");

 

snackbar using getx

Dialog box using GetX

Get.defaultDialog(title: "THIS IS DIALOG BOX USING FLUTTER GET X ",middleText: "GET x made Easy");

Dialog using GetX

Here is Simple Full Code with 3 Button to Perform above Operation using GetX

import 'package:flutter/material.dart';
import 'package:flutter_getx_demo/Page2.dart';
import 'package:get/get.dart';
void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      title: 'Flutter Demo',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(

        primarySwatch: Colors.blue,

        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(),
    );
  }
}

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

class _MyHomePageState extends State<MyHomePage> {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text("SHOW SNACKBAR"),

            FlatButton(onPressed: (){
              Get.snackbar("HI", "This is Snackbar using Flutter GetX");
            },   child: Text("Snackbar"),color: Colors.lightBlue,),

            SizedBox(
              height: 20,
            ),
            Text("SHOW  Dialog"),

            FlatButton(onPressed: (){
              Get.defaultDialog(title: "This is dialog using GetX Flutter");
            },   child: Text("Dialog"),color: Colors.lightBlue,),
            SizedBox(
              height: 20,
            ),
            Text("Go to Next Page"),

            FlatButton(onPressed: (){
              Get.to(Page2());
            },   child: Text("GO TO PAGE 2"),color: Colors.lightBlue,),


          ],
        ),
      ),
    );
  }
}



Output:

FLUTTER GETX DIALOG EXAMPLE FLUTTER GETX EXAMPLE SNACKBAR

 

Flutter Authentication | Flutter Fingerprint Scanner | Local Auth Package

0
Flutter fingerprint scanner authentication local auth
Flutter fingerprint scanner authentication local auth

Hi Guys, Welcome to Proto Coders Point, In this Flutter Tutorial we will demonstrate on how to implement flutter local_auth library to add fingerprint scanner to your android or iOS apps.

Video Tutorial 

Introduction of Local_Auth Flutter library

This local auth flutter plugin, will help you to perform local, i.e on-device authentication of the user.

By using this library you can add Biometric aithentication to login in your Android or iOS Application.

NOTE: This will work only on android 6.0.

Let’s Start

Flutter Authentication | Flutter Fingerprint Scanner | Local Auth Package

Step 1: Create new Flutter project

I am using android studio as my IDE to build/develop Flutter Apps, you may you any of you favourite IDE like : VSCode

In android Studio : File > New > New Flutter Project  > Finish

Step 2: Adding Local_auth dependencies

Once your new flutter project is ready or you might have opened existing flutter project.

Now, on your left side of your IDE you may see your project structure, under that find pubspec.yaml file where you need to add the local auth dependencie

pubspec.yaml

dependencies:
  local_auth: ^0.4.0+1

As you can see in below screenshot.

adding local auth plugin flutter

Step 3: Adding  USE_FINGERPRINT permission

USE_FINGERPRINT PERMISSION IN ANDROID

In your Flutter Project

android > app > src > main > AndroidManifest.xml

add the below permission

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.example.app">

  <uses-permission android:name="android.permission.USE_FINGERPRINT"/>  <!-- add this line -->

<manifest> 

as show in below screenshot

adding use finger permission android manifest

USE_FINGERPRINT PERMISSION IN IOS

In your Flutter Project

ios > Runner > Info.plist 

<key>NSFaceIDUsageDescription</key>
<string>Why is my app authenticating using face id?</string>

as shown in below screenshot

adding faceID touchID in flutter ios

Step 4: Flutter Code

main.dart

import 'package:flutter/material.dart';
import 'package:flutter_local_auth/HomePageAuthCheck.dart';
import 'package:local_auth/local_auth.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.blue,

        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: HomePageAuthCheck(),
    );
  }
}

HomePageAuthCheck.dart

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:local_auth/local_auth.dart';

class HomePageAuthCheck extends StatefulWidget {
  @override
  _HomePageAuthCheckState createState() => _HomePageAuthCheckState();
}

class _HomePageAuthCheckState extends State<HomePageAuthCheck> {
  //variable to check is biometric is there or not
  bool _hasBiometricSenson;

  // list of finger print added in local device settings
  List<BiometricType> _availableBiomatrics;


  String  _isAuthorized = "NOT AUTHORIZED";


  LocalAuthentication authentication = LocalAuthentication();

  //future function to check if biometric senson is available on device
  Future<void> _checkForBiometric() async{
    bool hasBiometric;

    try{
      hasBiometric = await authentication.canCheckBiometrics;
    } on PlatformException catch(e)
    {
      print(e);
    }

    if(!mounted) return;

    setState(() {
      _hasBiometricSenson = hasBiometric;
    });
  }

//future function to get the list of Biometric or faceID added into device
  Future<void> _getListofBiometric() async{
    List<BiometricType> ListofBiometric;

    try{
      ListofBiometric = await authentication.getAvailableBiometrics();
    } on PlatformException catch(e)
    {
      print(e);
    }

    if(!mounted) return;

    setState(() {
      _availableBiomatrics  = ListofBiometric;
    });
  }

  ////future function to check is the use is authorized or no
  Future<void> _getAuthentication() async{
    bool isAutherized = false;

    try{
      isAutherized = await authentication.authenticateWithBiometrics(
          localizedReason: "SCAN YOUR FINGER PRINT TO GET AUTHORIZED",
          useErrorDialogs: true,
          stickyAuth: false
      );
    } on PlatformException catch(e)
    {
      print(e);
    }

    if(!mounted) return;

    setState(() {
     _isAuthorized = isAutherized ? "AUTHORIZED" : "NOT AUTHORIZED";
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Flutter local Auth Package"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [

            Text(" Is BioMetric Available ? : $_hasBiometricSenson"),
            RaisedButton(onPressed: (){
             _checkForBiometric();
            },color:Colors.blue,child: Text("Check",style: TextStyle(color: Colors.white),),),


            Text(" List of Available Biomatric LIST : $_availableBiomatrics"),
            RaisedButton(onPressed: (){
              _getListofBiometric();
            },color:Colors.blue,child: Text("Check List",style: TextStyle(color: Colors.white),),),


            Text(" Is AUTHORIED ? : $_isAuthorized"),
            RaisedButton(onPressed: (){
              _getAuthentication();
            },color:Colors.blue,child: Text("AUTH",style: TextStyle(color: Colors.white),),),
          ],
        ),
      ),
    );
  }
}

then, thus you flutter application is ready with Fingerprint and FaceID authentication.

Explaination of above code and the properties been used.

First of all

I have Created an instance of a class i.e LocalAuthentication, This class is provided in local_auth package, this will help us in getting access to Local Authentication of the device.

LocalAuthentication authentication = LocalAuthentication();

By using this Class instance object we can make use of different properties such as:

  • canCheckBiometrics: This will return true is Biometric sensor is available.
  • getAvailableBiometrics: This will give list of Biometric finger print.
  • authenticationWithBiometrics: This will invoke a pop up, where it will ask you to “Scan for fingerprint/faceID”, then, if the authentication get matched then you are been authorized or you are unauthorized.

autherticationWithBiometrics has some more properties such as

  • localizedReason: Show a Text on the pop dialog box. flutter fingerprint authentication dialog box
  • useErrorDialog: When set to true, will show a proper message on the dailog screen, weather your device have Available Biometric if not then in alert diaolog it will show a message to go to setting to set a new Fingerprint. when no fingerprint authentication added in device
  • stickyAuth: When set to true, whenever you app goes into background and then you return back to app again, the Authentication process will continue again.

Function Created in above to code to check the same

1. To check if device have biometric sensor or not

//future function to check if biometric sensor is available on device
  Future<void> _checkForBiometric() async{
    bool hasBiometric;

    try{
      hasBiometric = await authentication.canCheckBiometrics;
    } on PlatformException catch(e)
    {
      print(e);
    }

    if(!mounted) return;

    setState(() {
      _hasBiometricSenson = hasBiometric;
    });
  }
hasbiometric

This function will return true if device has biometric sensor else false.

2. To get the list of fingerprint added in your local device

//future function to get the list of Biometric or faceID added into device
  Future<void> _getListofBiometric() async{
    List<BiometricType> ListofBiometric;

    try{
      ListofBiometric = await authentication.getAvailableBiometrics();
    } on PlatformException catch(e)
    {
      print(e);
    }

    if(!mounted) return;

    setState(() {
      _availableBiomatrics  = ListofBiometric;
    });
  }
list of finger print available flutter

This will return array list of fingerprint

3. To check fingerprint authentication

////future function to check is the use is authorized or no
 Future<void> _getAuthentication() async{
   bool isAutherized = false;

   try{
     isAutherized = await authentication.authenticateWithBiometrics(
         localizedReason: "SCAN YOUR FINGER PRINT TO GET AUTHORIZED",
         useErrorDialogs: true,
         stickyAuth: false
     );
   } on PlatformException catch(e)
   {
     print(e);
   }

   if(!mounted) return;

   setState(() {
    _isAuthorized = isAutherized ? "AUTHORIZED" : "NOT AUTHORIZED";
   });
 }

This function will invoke a dialog box when user will be asked to touch the fingerprint scanner to get access to further app process.

Flutter app local login using fingerprint scanner, access to app with local finger print authentication

Notes App – To do list app in Flutter – using Provider

0
flutter todo app tutorial using provider app

Hi Guys, Welcome to Proto Coders Point, In this flutter tutorial we will discuss on flutter provider,

By using provider in flutter we will develop an simple Notes app or to do list app in flutter.

DEMO

To do list Notes app flutter GIF IMAGE

What is Flutter provider?

A Provider in flutter is a wrapper around Inherited widget to make it easier to use & more reusable.

By using flutter provider instead of manual writting inheritedwidget, you get simplied alocation of resourse & greatly reduce boilerplate over making new class each time when data gets changed.

For Example: If any data gets changed and need to updated into the App UI, then Instead of rebuilding full hierarchy of Widgets, we can simply Update value of Flutter Provider Consumer Widgets.

Learn more about Flutter Provider

Beginner in provider? Have a look at basic of it : https://protocoderspoint.com/flutter-provider-for-beginners-tutorial-with-example/

So let’s begin…

Video Tutorial

Creating Notes/ To do List app using flutter – provider

Step 1: Create a new Flutter Project

Offcourse you need to create new flutter project, In my case i am making use of android studio as my IDE to develop flutter applications.

Step 2: Add required dependencies – Provider library and Slidable library

Then, as we are building Notes app/to do list app in flutter by using Provider class we need to add Provider dependencies in our flutter project.

And then, we also need Slidable  so that using can easily slide the listTile to delete or remove any notes to do.

Slidabe listTile to delete list

slidable listtile flutter to delete list

add this both dependencies in pubspec.yaml file as soon in below screenshot

adding dependencies provider and slidable

Learn more about this plugin library

Provider official Site

Slidable Official Site

Step 3: Create 2 folder in lib directory and create dart files

Then in lib directory of your flutter project, you need to create 2 directory by name

  • model : Will have 2 files : Notes.dart and NotesProvider.dart
  • Screen : Will have 1 file : Home_Screen.dart

Create respective dart files under those folder as shown below

creating directory and files in flutter

Step 4: Source code

main.dart

import 'package:flutter/material.dart';
import 'package:flutter_note_app_provider/models/NotesProvider.dart';
import 'package:flutter_note_app_provider/screens/Home_Screen.dart';
import 'package:provider/provider.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (context)=>NotesProviders(),
      child: MaterialApp(
        title: 'Flutter Demo',
        debugShowCheckedModeBanner: false,
        theme: ThemeData(
          primarySwatch: Colors.blue,
          visualDensity: VisualDensity.adaptivePlatformDensity,
        ),
        home: Home_Screen()
      ),
    );
  }
}



Under Model folder

Notes.dart

In Notes Class we have 2 field to hold data i.e title,description and a Constructor.

This class will work and data model to handle them.

class Notes{
  String title;
  String description;

  Notes(this.title,this.description);
}

NotesProviders.dart

In NotesProviders class has a list of type<Notes> where we gonna store all the data the user create to store ToDo List notes.

It has 2 function

addNotes: that will help us to add data to the List of Array notes.

removeNotes: that will help us deleting/removing notes from the List

NoteProvider class is extended with ChangeNotifier because whenever any data is been changed or when user add notes, the data consumer will get notified, for that we make use of  notifyListeners(); to notify all the data consumer.

import 'package:flutter/cupertino.dart';
import 'package:flutter_note_app_provider/models/Notes.dart';
class NotesProviders extends ChangeNotifier {

  //Notes List
 List<Notes> _notes = new List<Notes>();

 List<Notes> get getNotes{
   return _notes;
 }

// function to add data to list of notes 
 void addNotes(String title,String descriptions)
 {
   Notes note = new Notes(title, descriptions);

   _notes.add(note);

    notifyListeners();
 }

 // function to remove or delete notes by using list index position
 void removeNotes(int index)
 {
   _notes.removeAt(index);
   notifyListeners();
 }


}


Screen Folder

Home_Screen.dart

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_note_app_provider/models/Notes.dart';
import 'package:flutter_note_app_provider/models/NotesProvider.dart';
import 'package:provider/provider.dart';
import 'package:flutter_slidable/flutter_slidable.dart';

// ignore: camel_case_types
class Home_Screen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.purple[600],
     appBar: AppBar(
         titleSpacing: 0.0,
       toolbarHeight: 200,
       title: Image.network("https://9to5mac.com/wp-content/uploads/sites/6/2019/11/how-to-quickly-select-move-delete-notes-iphone-ipad-two-finger-tap.jpeg?quality=82&strip=all",fit: BoxFit.cover,)
     ),

      body: Padding(
        padding: const EdgeInsets.all(8.0),
        child: Consumer<NotesProviders>(
          builder: (context,NotesProviders data,child){
            return data.getNotes.length !=0 ? ListView.builder(
              itemCount: data.getNotes.length,
              itemBuilder: (context,index){
                return CardList(data.getNotes[index],index);
              },
            ): GestureDetector(onTap: (){
              showAlertDialog(context);
            },child: Center(child: Text("ADD SOME NOTES NOW",style: TextStyle(color: Colors.white,),)));
          },
        ),
      ),

      floatingActionButton: FloatingActionButton(onPressed: () {
        showAlertDialog(context);
      },
          backgroundColor: Colors.white,
          child: Icon(Icons.add,color: Colors.black,),
      ),
    );

  }

}

// ignore: must_be_immutable
class CardList extends StatelessWidget {
  final Notes notes;
  int index;

  CardList(this.notes,this.index);

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(2.0),
      child:Slidable(
        actionPane: SlidableDrawerActionPane(),
        actionExtentRatio: 0.25,
        child: Container(
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.only(
              bottomLeft: Radius.circular(10),
              topLeft: Radius.circular(10),

            )
          ),
          child: ListTile(
           leading: Icon(Icons.note),
              title: Text(notes.title),
            subtitle: Text(notes.description),
            trailing: Icon(Icons.arrow_forward_ios,color: Colors.black26,),
          ),
        ),

        secondaryActions: <Widget>[
          IconSlideAction(
            caption: 'Delete',
            color: Colors.red,
            icon: Icons.delete,
            onTap: (){
              print("HELLO DELETED");
              Provider.of<NotesProviders>(context,listen: false).removeNotes(index);
            }
          ),
        ],
      ),
    );
  }
}

showAlertDialog(BuildContext context) {

  TextEditingController _Title = TextEditingController();
  TextEditingController _Description = TextEditingController();
  // Create button
  Widget okButton = FlatButton(
    child: Text("ADD NOTE"),
    onPressed: () {
      Provider.of<NotesProviders>(context,listen: false).addNotes(_Title.text, _Description.text);
      Navigator.of(context).pop();
    },
  );

  // Create AlertDialog
  AlertDialog alert = AlertDialog(
    title: Text("ADD A NEW NOTE "),
    content: Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        TextField(
          controller: _Title,
          decoration: InputDecoration(hintText: "Enter Title"),
        ),
        TextField(
          controller: _Description,
          decoration: InputDecoration(hintText: "Enter Description"),
        ),
      ],
    ),
    actions: [
      okButton,
    ],
  );

  // show the dialog
  showDialog(
    context: context,
    builder: (BuildContext context) {
      return alert;
    },
  );
}


 

Download the Project from GITHUB