Firebase Integration, Firebase Authentication, Firestore | RRTutors

Last updated Jul 13, 2019

Hello Guys,

In this tutorial we are going to learn about Flutter Firebase authentication, Firestore integration.

Step 1:
Create a project in Any IDE.

Step 2:
Login to Firebase console

Then Create a project.
Once Project created you will navigates to Dashboard. There you will find the options like Android,Ios,Web
Select Android and download google-services.json file and put this inside your android app folder.

in Android Add 

classpath 'com.google.gms:google-services:4.2.0'

in Project level gradle file

and in App level gradle file add 

implementation 'com.google.firebase:firebase-core:17.0.0' in dependencies block and
apply plugin: 'com.google.gms.google-services' at the end of the file

Now go to pubspec.yaml file and add below dependencies under flutter SDK

cloud_firestore: ^0.12.7
firebase_auth: ^0.11.1+7

    

 

Before going to next step Read my previous post Flutter SQFlite Integration

Step 3:
Create a class files like below

Splash Screen

import 'package:flutter/material.dart';

import 'databases/UserDatabase.dart';
import 'home/home.dart';
import 'main.dart';
import 'models/user.dart';
import 'signup_login/LoginPage.dart';

class SplashPage extends StatefulWidget{
  @override
  State createState() {
    // TODO: implement createState
    return SplashState();
  }

}

class SplashState extends State
{

  int login=101;
  int loginData;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    loginData=login;
    new Future.delayed(const Duration(seconds: 1), () {
      UserDatabase.instance.getUser().then((result){
        setState(() {
          loginData=result;
          if(loginData==0)
            Navigator.pushReplacementNamed(context, "/login");
          else  Navigator.pushReplacementNamed(context, "/home");
          print("Called Return value on state  $loginData");
        });
      });

    });

  }
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return MaterialApp(
        debugShowCheckedModeBanner: false,
        home: Container(
          child: Image.asset("splash_img.png",fit: BoxFit.cover,),

        ));

  }
}

Login Screen

 

import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter_firestroe/databases/UserDatabase.dart';
import 'package:flutter_firestroe/models/user.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

class LoginPage extends StatefulWidget{
  @override
  State createState() {
    // TODO: implement createState
    return LoginState();
  }

}
class LoginState extends State
{
  final _formKey = GlobalKey();
  final _scaffoldKey = GlobalKey();
  final _emailEditController=TextEditingController();
  final _passwordController=TextEditingController();
  final FocusNode _mobileFocus = FocusNode();
  final FocusNode _passwordFocus = FocusNode();
  FirebaseAuth _auth=FirebaseAuth.instance;
  Firestore _firestore=Firestore.instance;

  String email_pattern = r'^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$';
  Size size;
  @override
  Widget build(BuildContext context) {
    size = MediaQuery.of(context).size;
    return new Scaffold(
      key: _scaffoldKey,
      backgroundColor: Colors.transparent,
      body: Stack(
        children:[
          Container(
            height: size.height,

            decoration:BoxDecoration(

                gradient: LinearGradient(
                  colors: [Colors.deepOrange,Colors.orange/*,const Color(0XFF388e3c)*/,],

                ),
                borderRadius: BorderRadius.only(

                  topRight: Radius.circular(20),
                  topLeft: Radius.circular(20),
                )
            ) ,
          ),
          Container(
          height: size.height,

           decoration:BoxDecoration(

             gradient: LinearGradient(
                 colors: [const Color(0XFF424242),const Color(0XFF303030),const Color(0XFF212121),],

             ),
             borderRadius: BorderRadius.only(
                 bottomLeft: Radius.circular(480),
                topRight: Radius.circular(20),
                topLeft: Radius.circular(20),
             )
           ) ,
          ),

          Padding(
            padding: EdgeInsets.only(left: 20,right: 20),
            child: Form(
                key: _formKey,
                child:
                Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Icon(Icons.filter_drama,size: 100,
                      color: Colors.white,
                    ),
                    SizedBox(height: 20,),

                    TextFormField(
                      controller: _emailEditController,
                      textInputAction: TextInputAction.next,
                      validator: (value){
                        RegExp regex =RegExp(email_pattern);
                        if (!regex.hasMatch(value))
                          return 'Enter Valid Email';
                        else
                          return null;
                      },
                      keyboardType: TextInputType.emailAddress,
                      style: getTextStyle(),
                      decoration: customInputDecoration("Enter email id"),),
                    SizedBox(height: 20,),
                    TextFormField(
                      textInputAction: TextInputAction.done,
                      controller: _passwordController,
                      keyboardType: TextInputType.text,

                      obscureText: true,
                      focusNode: _passwordFocus,
                      validator: (value){
                        if(value.isEmpty)
                        {
                          return "Enter Password";
                        }
                        return null;
                      },
                      style: getTextStyle(),
                      decoration: customInputDecoration("Enter password"),
                    ),
                    SizedBox(height: 20,),
                    RaisedButton(onPressed: (){

                      if(_formKey.currentState.validate())
                      {
                        showDialog(context:
                        context,
                            barrierDismissible: false,
                            builder: (_)=>Material(
                              color: Colors.transparent,
                              child: Center(
                                child: Column(
                                  mainAxisSize: MainAxisSize.min,
                                  children: [
                                    CircularProgressIndicator(),
                                    Text("Connecting..."),
                                  ],
                                ),
                              ),
                            )


                        );

                        _auth.signInWithEmailAndPassword(email: _emailEditController.text, password: _passwordController.text)
                        .then((res){
                          print(res.uid);
                          _firestore.collection("users").document(res.uid).get().then(
                              (_snapshot){

                                UserDatabase.instance.insertUser(  User.fromMap(_snapshot.data)).then((res){

                                  Navigator.pop(context);
                                  _scaffoldKey.currentState.showSnackBar(SnackBar(content: Text("Succesfully LogIn"+res.toString())));
                                  Navigator.pushReplacementNamed(context, "/home");
                                });

                              }
                          ).catchError((err){
                            Navigator.pop(context);
                            _scaffoldKey.currentState.showSnackBar(SnackBar(content: Text(err.message)));
                          });

                        }).catchError((err){
                          Navigator.pop(context);
                          _scaffoldKey.currentState.showSnackBar(SnackBar(content: Text(err.message)));
                        });
                      }

                    }, shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(18),
                    ),
                      color: Colors.orange,
                      child: Text("Login", style: TextStyle(color: Colors.white,fontSize: 20),),
                    ),

                    FlatButton(
                      child: Text("Don't have account, Signup?",style: TextStyle(color: Colors.white),),
                      onPressed: (){
                        Navigator.pushReplacementNamed(context, "/signup");
                      },
                    )
                  ],
                )
            ),
          )
        ] ,
      ),
    );
  }
  TextStyle getTextStyle(){
    return TextStyle(
        fontSize: 18,
        color: Colors.white
    );
  }

  InputDecoration customInputDecoration(String hint)
  {

    return InputDecoration(
      hintText: hint,
      hintStyle: TextStyle(
          color: Colors.white70
      ),
      contentPadding: EdgeInsets.all(10),
      enabledBorder: OutlineInputBorder(
          borderRadius: BorderRadius.circular(12),
          borderSide: BorderSide(
              color: Colors.white
          )
      ),
      focusedBorder: OutlineInputBorder(
          borderRadius: BorderRadius.circular(8),
          borderSide: BorderSide(
              color: Colors.white
          )
      ),

    );
  }
  /*[const Color(0XF46326),const Color(0XF57b28),]*/
}

FirebaseAuth _auth=FirebaseAuth.instance;

Firestore _firestore=Firestore.instance;

These two lines will create FirebaseAuthentication, Firestore instances.

Home Screen

import 'package:flutter/material.dart';
import 'package:flutter_firestroe/databases/UserDatabase.dart';
import 'package:flutter_firestroe/models/user.dart';

class Homepage extends StatefulWidget{
  @override
  State createState() {
    // TODO: implement createState

    return HomeState();
  }

}

class HomeState extends State{
  Size size;
  User user;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    UserDatabase.instance.getUserData().then((result){
      setState(() {
        user=result;
      });

    });
  }
  @override
  Widget build(BuildContext context) {
    size=MediaQuery.of(context).size;
    return Scaffold(
    backgroundColor: Colors.transparent,
      body: Stack(
        children: [
          Container(
            height: size.height,

            decoration:BoxDecoration(

                gradient: LinearGradient(
                  colors: [Colors.deepOrange,Colors.orange/*,const Color(0XFF388e3c)*/,],

                ),
                borderRadius: BorderRadius.only(

                  topRight: Radius.circular(20),
                  topLeft: Radius.circular(20),
                  bottomLeft: Radius.circular(20),
                  bottomRight: Radius.circular(20),
                )
            ) ,
          ),
          Scaffold(
            appBar: AppBar(
              title: Text("Home"),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.only(
                  topRight: Radius.circular(20),
                  topLeft: Radius.circular(20),
                )
              ),
              backgroundColor: Colors.deepOrange,
            ),
            backgroundColor: Colors.transparent,
            body: Center(
              child: Column(
                mainAxisSize: MainAxisSize.min,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [

                  Column(

                    mainAxisAlignment: MainAxisAlignment.center,

                    children: [
                         Center(
                          child: (user==null)?null:Text("Welcome User "+user.name,
                            style:TextStyle(
                              color: Colors.white,
                              fontSize: 22,
                            ) ,),
                        ),
                      Padding(
                        padding: const EdgeInsets.all(12.0),
                        child: RaisedButton(
                            onPressed: (){
                              UserDatabase.instance.deleteUser(user.email).then((res){
                              if(res==1)
                              {
                                  Navigator.pushReplacementNamed(context, "/login");
                              }

                              });

                            },
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(15),

                            ),
                            color:Colors.pink,
                            child: Text("Logout", style: TextStyle(color: Colors.white
                            ),)
                        ),
                      )
                    ],
                  ),

                ],
              ),
            ),
          ),
        ],

      )
    );
  }

}

get the complete code at  rrtutors  github account

 

TAGS : Flutter, Flutter Firebase, Flutter Firebase Authentication, FireStore, Flutter Routes, Flutter Navigators

Flutter Local database, SQFlite

Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

1807 Views