Flutter provider login example firebase auth email password
Flutter provider login example firebase auth email password

Hi Guys, Welcome to Proto Coders Point, In this flutter tutorial we will create a flutter app for demonstrating “Firebase login example using provider package”.

Video Tutorial for Firebase login using flutter provider

What is Flutter Provider?

In Short, Provider flutter is like a way to use an InheritedWidget.

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 basic of flutter provider

Video Tutorial of Flutter Provider


Flutter provider login example – Firebase login example using Provider

So Let’s begin building Flutter App using Provider firebase login registration example.

Step 1: Create a new Flutter Project

Offcourse, you need to create a new Flutter project, In my case i am using Android Studio as my IDE to build/developer flutter applications.


Step 2 : Connecting Flutter app to Firebase console

Check out this article tutorial, step by step process to add firebase to flutter 

OR

Watch video tutorial to add firebase to your flutter app

So now our flutter project is been connected to our firebase console.


Step 3:  Add Required Dependencies

So as you now we are adding authentication feature using Firebase service i.e. Firebase Authentication so for that we need firebase_auth dependencies, and by using provider flutter we will implement provider login & Registration to firebase so for that we need provider dependencies.

Open pubspec.yaml file and all  both the dependencies

dependencies:
  firebase_auth: # for latest version visit official site
  provider: ^4.3.2+3

Step 4 : Create Folder

Under lib directory of your flutter project create 2 folders namely as stated below:

flutter provider login example project structure

ProviderHelper : This will have 1 dart file “ProviderState.dart”, that will help us in registration and Login to the flutter application using firebase auth functions.

Screens : Here we will have 3 dart file,
First for Registration UI Screen :  Used to register to firebase auth.
Second for Login UI Screen : Used to login using firebase auth.
Third for Dashboard Page :  after success login page.


Step 5 : Code

Under ProviderHelper folder create a dart file by name : ProviderState.dart and copy the code as given below.

ProviderState.dart

import 'dart:math';

import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/cupertino.dart';

class ProviderState extends ChangeNotifier{

  String _uid;
  String _email;

  String get getUid =>_uid;
  String get getEmail => _email;

  FirebaseAuth _auth = FirebaseAuth.instance;

  Future<bool> signUpUser(String email,String password) async{
    bool retval = false;

    try{
      UserCredential userCredential = await _auth.createUserWithEmailAndPassword(email: email, password: password);

      if(userCredential.user != null)
        {
          _uid = userCredential.user.uid;
          _email = userCredential.user.email;
          return retval = true;
        }
    }catch(e)
    {
      print(e);
    }

    return retval;
  }

  Future<bool> LoginUser(String email,String password) async{
    bool retval = false;

    try{
      UserCredential userCredential = await _auth.signInWithEmailAndPassword(email: email, password: password);

      if(userCredential.user != null)
      {
        _uid = userCredential.user.uid;
        _email = userCredential.user.email;
        return retval = true;
      }
    }catch(e)
    {
      print(e);
    }

    return retval;
  }
}

In above code we make use of firebase auth instance using which we can call firebase auth methods:
createUserWithEmailAndPassword : This Method accept 2 parameter i.e. Email & Password string, When this is called  it will create auth user in firebase auth console.
signInWithEmailAndPassword : This Method also accept 2 parameter i.e. Email & Password string, When this is called it will check in firebase auth if user account is exist, if yes then user will be logged in to the app.


UI Screen

Under Screens folder create dart file as below and add respective code

ProviderRegistration.dart

flutter registration firebase

import 'package:flutter/material.dart';
import 'package:flutter_login_ui/ProviderExample/ProviderHelper/ProviderState.dart';
import 'package:flutter_login_ui/ProviderExample/Screens/ProviderLogin.dart';
import 'package:flutter_svg/svg.dart';
import 'package:provider/provider.dart';
import 'package:velocity_x/velocity_x.dart';
class ProviderRegistration extends StatefulWidget {
  @override
  _ProviderRegistrationState createState() => _ProviderRegistrationState();
}

class _ProviderRegistrationState extends State<ProviderRegistration> {
  final TextEditingController firstn = TextEditingController();
  final TextEditingController lastn = TextEditingController();
  final TextEditingController email = TextEditingController();
  final TextEditingController password = TextEditingController();

    void _signUp(String email,String password,BuildContext context) async{
      ProviderState _providerState = Provider.of<ProviderState>(context,listen: false);
      try{
        if(await _providerState.signUpUser(email, password)){
          Navigator.pushReplacement(context, MaterialPageRoute(builder: (context)=>ProviderLogin()));
        }
      }catch(e)
      {
        print(e);
      }

    }
  @override
  Widget build(BuildContext context) {

    return Scaffold(
        body: SafeArea(
          child: Stack(
            children: [
              Container(
                decoration: BoxDecoration(
                    image: DecorationImage(
                        image: AssetImage("images/assets/backgroundUI.png"),
                        fit: BoxFit.cover
                    )
                ),
              ),
              Padding(
                padding: const EdgeInsets.fromLTRB(20,40 , 20, 0),
                child: SingleChildScrollView(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Container(
                          height: 100,
                          width: 100,
                          child: SvgPicture.asset("images/assets/xing.svg")),
                      HeightBox(10),
                      "Registration".text.color(Colors.white).size(20).make(),
                      HeightBox(
                          20
                      ),
                      Padding(
                        padding: const EdgeInsets.fromLTRB(30, 0, 30, 0),
                        child: TextField(
                          controller: firstn,
                          decoration: InputDecoration(
                            hintText: 'First Name',
                            hintStyle: TextStyle(color: Colors.white),
                            enabledBorder: OutlineInputBorder(
                              borderRadius: new BorderRadius.circular(10.0),
                              borderSide: BorderSide(
                                  color: Colors.white
                              ),
                            ),
                            focusedBorder: OutlineInputBorder(
                                borderRadius: new BorderRadius.circular(10.0),
                                borderSide: BorderSide(
                                    color: Colors.blue[400]
                                )
                            ),
                            isDense: true,                      // Added this
                            contentPadding: EdgeInsets.fromLTRB(10, 20, 10, 10),
                          ),
                          cursorColor: Colors.white,
                          style: TextStyle(color: Colors.white),
                        ),
                      ),
                      HeightBox(
                          20
                      ),
                      Padding(
                        padding: const EdgeInsets.fromLTRB(30, 0, 30, 0),
                        child: TextField(
                          controller: lastn,
                          decoration: InputDecoration(
                            hintText: 'Last Name',
                            hintStyle: TextStyle(color: Colors.white),
                            enabledBorder: OutlineInputBorder(
                              borderRadius: new BorderRadius.circular(10.0),
                              borderSide: BorderSide(
                                  color: Colors.white
                              ),
                            ),
                            focusedBorder: OutlineInputBorder(
                                borderRadius: new BorderRadius.circular(10.0),
                                borderSide: BorderSide(
                                    color: Colors.blue[400]
                                )
                            ),
                            isDense: true,                      // Added this
                            contentPadding: EdgeInsets.fromLTRB(10, 20, 10, 10),
                          ),
                          cursorColor: Colors.white,
                          style: TextStyle(color: Colors.white),
                        ),
                      ),
                      HeightBox(
                          20
                      ),
                      Padding(
                        padding: const EdgeInsets.fromLTRB(30, 0, 30, 0),
                        child: TextField(
                          controller: email,
                          decoration: InputDecoration(
                            hintText: 'Email',
                            hintStyle: TextStyle(color: Colors.white),
                            enabledBorder: OutlineInputBorder(
                              borderRadius: new BorderRadius.circular(10.0),
                              borderSide: BorderSide(
                                  color: Colors.white
                              ),
                            ),
                            focusedBorder: OutlineInputBorder(
                                borderRadius: new BorderRadius.circular(10.0),
                                borderSide: BorderSide(
                                    color: Colors.blue[400]
                                )
                            ),
                            isDense: true,                      // Added this
                            contentPadding: EdgeInsets.fromLTRB(10, 20, 10, 10),
                          ),
                          cursorColor: Colors.white,
                          style: TextStyle(color: Colors.white),
                        ),
                      ),
                      HeightBox(
                          20
                      ),
                      Padding(
                        padding: const EdgeInsets.fromLTRB(30, 0, 30, 0),
                        child: TextField(
                          controller: password,
                          decoration: InputDecoration(
                            hintText: 'Password',
                            hintStyle: TextStyle(color: Colors.white),
                            enabledBorder: OutlineInputBorder(
                              borderRadius: new BorderRadius.circular(10.0),
                              borderSide: BorderSide(
                                  color: Colors.white
                              ),
                            ),
                            focusedBorder: OutlineInputBorder(
                                borderRadius: new BorderRadius.circular(10.0),
                                borderSide: BorderSide(
                                    color: Colors.blue[400]
                                )
                            ),
                            isDense: true,                      // Added this
                            contentPadding: EdgeInsets.fromLTRB(10, 20, 10, 10),
                          ),
                          cursorColor: Colors.white,
                          style: TextStyle(color: Colors.white),
                        ),
                      ),
                      HeightBox(20),
                      GestureDetector(
                          onTap:(){
                            final close = context.showLoading(msg: "Loading");
                            Future.delayed(4.seconds, close); // Removes toast after 2 seconds
                           // RegisterUser();

                            _signUp(email.text, password.text, context);
                          },
                          child: "Sign-Up".text.white.light.xl.makeCentered().box.white.shadowOutline(outlineColor: Colors.grey).color(Color(0XFFFF0772)).roundedLg.make().w(150).h(40)),
                      HeightBox(140),

                    ],
                  ),
                ),
              )
            ],
          ),
        ),
        bottomNavigationBar: GestureDetector(
          onTap: (){
            Navigator.pushReplacement(context, MaterialPageRoute(builder: (context)=>ProviderLogin()));
          },
          child: RichText(text: TextSpan(
            text: 'New User?',
            style: TextStyle(fontSize: 15.0, color: Colors.black),
            children: <TextSpan>[
              TextSpan(
                text: ' Login Now',
                style: TextStyle(
                    fontWeight: FontWeight.w600,
                    fontSize: 18,
                    color: Color(0XFF4321F5)),
              ),
            ],
          )
          ).pLTRB(20, 0, 0, 15),
        )
    );
  }
}

ProviderLogin.dart

flutter login provider using firebase auth

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_login_ui/GetXHelper/FirebaseController.dart';
import 'package:flutter_login_ui/ProviderExample/ProviderHelper/ProviderState.dart';
import 'package:flutter_login_ui/ProviderExample/Screens/ProviderDashboard.dart';
import 'package:flutter_login_ui/ProviderExample/Screens/ProviderRegistration.dart';
import 'package:flutter_login_ui/Screen/Dashboard.dart';
import 'package:flutter_login_ui/Screen/ForgotPassword.dart';
import 'package:flutter_login_ui/Screen/RegistrationPage.dart';
import 'file:///C:/Android%20Studio%20Stuff/Flutter%20Project/flutter_login_ui/lib/Widgets/SocialSignWidgetRow.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:get/get.dart';
import 'package:provider/provider.dart';
import 'package:velocity_x/velocity_x.dart';


class ProviderLogin extends StatefulWidget {
  @override
  _ProviderLoginState createState() => _ProviderLoginState();
}

class _ProviderLoginState extends State<ProviderLogin> {

  TextEditingController email = TextEditingController();
  TextEditingController pass = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: SafeArea(
          child: Stack(
            children: [
              Container(
                decoration: BoxDecoration(
                    image: DecorationImage(
                        image: AssetImage("images/assets/backgroundUI.png"),
                        fit: BoxFit.cover
                    )
                ),
              ),
              Padding(
                padding: const EdgeInsets.fromLTRB(20,40 , 20, 0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Container(
                        height: 100,
                        width: 100,
                        child: SvgPicture.asset("images/assets/xing.svg")),
                    HeightBox(10),
                    "Login".text.color(Colors.white).size(20).make(),
                    HeightBox(
                        20
                    ),
                    Padding(
                      padding: const EdgeInsets.fromLTRB(30, 0, 30, 0),
                      child: TextField(
                        controller: email,
                        decoration: InputDecoration(
                          hintText: 'Email',
                          hintStyle: TextStyle(color: Colors.white),
                          enabledBorder: OutlineInputBorder(
                            borderRadius: new BorderRadius.circular(10.0),
                            borderSide: BorderSide(
                                color: Colors.white
                            ),
                          ),
                          focusedBorder: OutlineInputBorder(
                              borderRadius: new BorderRadius.circular(10.0),
                              borderSide: BorderSide(
                                  color: Colors.blue[400]
                              )
                          ),
                          isDense: true,                      // Added this
                          contentPadding: EdgeInsets.fromLTRB(10, 20, 10, 10),
                        ),
                        cursorColor: Colors.white,
                        style: TextStyle(color: Colors.white),
                      ),
                    ),
                    HeightBox(
                        20
                    ),
                    Padding(
                      padding: const EdgeInsets.fromLTRB(30, 0, 30, 0),
                      child: TextField(
                        controller: pass,
                        decoration: InputDecoration(
                          hintText: 'Password',
                          hintStyle: TextStyle(color: Colors.white),
                          enabledBorder: OutlineInputBorder(
                            borderRadius: new BorderRadius.circular(10.0),
                            borderSide: BorderSide(
                                color: Colors.white
                            ),
                          ),
                          focusedBorder: OutlineInputBorder(
                              borderRadius: new BorderRadius.circular(10.0),
                              borderSide: BorderSide(
                                  color: Colors.blue[400]
                              )
                          ),
                          isDense: true,                      // Added this
                          contentPadding: EdgeInsets.fromLTRB(10, 20, 10, 10),
                        ),
                        cursorColor: Colors.white,
                        style: TextStyle(color: Colors.white),
                      ),
                    ),
                    HeightBox(20),

                    GestureDetector(onTap: (){
                      Get.to(ForgotPassword());
                    },
                      child: Text("Forgot Password ? Reset Now",style: TextStyle(color: Colors.white),),),

                    HeightBox(10),
                    GestureDetector(
                        onTap: (){
                          print("Login Clicked Event");
                          _Login(email.text, pass.text, context);
                        },
                        child: "Login".text.white.light.xl.makeCentered().box.white.shadowOutline(outlineColor: Colors.grey).color(Color(0XFFFF0772)).roundedLg.make().w(150).h(40)),
                    HeightBox(20),



                  ],
                ),
              )
            ],
          ),
        ),
        bottomNavigationBar: GestureDetector(
          onTap: (){
            Navigator.pushReplacement(context, MaterialPageRoute(builder: (context)=>ProviderRegistration()));
          },
          child: RichText(text: TextSpan(
            text: 'New User?',
            style: TextStyle(fontSize: 15.0, color: Colors.black),
            children: <TextSpan>[
              TextSpan(
                text: ' Register Now',
                style: TextStyle(
                    fontWeight: FontWeight.w600,
                    fontSize: 18,
                    color: Color(0XFF4321F5)),
              ),
            ],
          )
          ).pLTRB(20, 0, 0, 15),
        )
    );
  }
  void _Login(String email,String password,BuildContext context) async{
    ProviderState _providerState = Provider.of<ProviderState>(context,listen: false);
    try{
      if(await _providerState.LoginUser(email, password)){
        Navigator.pushReplacement(context, MaterialPageRoute(builder: (context)=>ProviderDashboard()));
      }
    }catch(e)
    {
      print(e);
    }

  }
}






ProviderDashboard.dart

import 'package:flutter/material.dart';
import 'package:flutter_login_ui/ProviderExample/ProviderHelper/ProviderState.dart';
import 'package:provider/provider.dart';

class ProviderDashboard extends StatelessWidget {
  @override
  Widget build(BuildContext context) {

    ProviderState _providerState = Provider.of<ProviderState>(context,listen: false);
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text("UID: ${_providerState.getUid}"),
            Text("Email : ${_providerState.getEmail}"),
            RaisedButton(onPressed: (){
              //logout
              //controller.signout();
            },child: Text("Sign Out "),),

          ],
        ),
      ),
    );
  }
}

Then, In dashboard page, i am just showing Firebase UID and Email address of Signed In user.

Dashboard flutter example


Notes App – to do list app using Flutter Provider