Flutter firebase authentication using getx library

Hi Guys,Welcome to Proto Coders Point, In this flutter tutorial we will connect flutter to firebase console project & also implement flutter firebase authentication using getx library.

So Let’s Begin.

VIDEO TUTORIAL 

Create a new Flutter Project & Connect it to Firebase Console Project

  1. Create a new Flutter Project

    OffCourse you need to Create a new Flutter Project – In Recommend you to use Android-Studio as your IDE for Building Flutter Application.

  2. How to Connect Flutter app to Firebase – Android

    Adding/Create a new Project in Firebase Console

    Connecting Flutter to Firebase 1 add project

    Select Platform  –
    I have selected Android, Because this tutorial is only on Android

    Registering your Flutter android to Firebase

    You will find your Flutter android package name under

    project > Android > app > src > main > AndroidManifest.xml

    Copy android package name and paste it into firebase console app registration as soon below.

    adding firebase to your flutter app

     

    Then, Hit Register app
    Firebase will give you a google-services.json file a show below, you need to just download it and paste in your flutter project under
    project > Android > app
    coping google services in app folder of flutter project Last Step add all the dependencies, as guided by Firebase app registration steps
    adding firebase SDK dependencies -minThen after completing all the above task you need to add a flutter plugin dependencies i.e firebase_core:
    and then in flutter main.dart file you need to call  Firebase.initializeApp();  so that your flutter app will call firebase server and your app will get connected to firebase console.
    firebase initializeAppSo Now your Flutter App is been Connect to Firebase Console Project
    It’s time to Start Implementing Flutter Firebase Auth using Flutter Getx Library.

Implementation of Flutter Firebase Authentication using GetX Library

In this project we have designed a Beautiful UI design for Login and Registration page by using VelocityX library

You may download/clone this flutter login & Registration UI from GitHub or check this tutorial for UI design.
GitHub: https://github.com/RajatPalankar8/Flutter_Login_Registration_UI
Website: https://protocoderspoint.com/flutter-login-register-page-ui-design-adobexd-using-velocity-x-library/

So, For this same Flutter UI design we gonna add Flutter Firebase Authentication. So let’s Begin.

Step 1 : Add Required Dependencies

flutter_svg:
velocity_x:
get:
cloud_firestore: ^0.14.1+3
firebase_auth:

Add this all dependencies in pubspec.yaml file under dependencies tag:

flutter_svg: To show svg image in our UI design.
velocity_x: To build UI design much faster.
get: As this Tutorial is on Getx Firbase Auth Example.
cloud_firebase: Need to send register/store user data in Firebase cloud store.
firebase_auth: To send create Auth and Login Auth Request to Flutter Firebase Authentication service.

Step 2: Turn on Authentication service in Firebase Console

Then, now Go to Firebase Console, open your Flutter firebase project and on the left navigation you may see Authentication open, go into it.

There you need to turn on Firebase Email/password Auth.
firebase turn on authentication email passwordStep 3 : Create a Cloud Firestore database

Just go to Cloud Firestore and Hit that Create Database button and then change the Rules to any one can access

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write;   // here allow read, write means any one can access your data // which is not the safe method for Real project
    }
  }
}

This is how our registered user data will be store in firebase firestore

So, Now we are done will all the Firebase setup for Flutter registration email, Let’s Check the flutter dart coding.

Step 4: Coding in Flutter Project

Here is the Project Structure with all the dart file.

We have 3 Directorys

  • GetXHelper : Here we have FirebaseController.dart file which will help you to communicate with Firebase Auth and Firestore server.
  • Screen : In the Folder we have 3 Pages
    Login Page
    Registration Page
    Dashboard Page
  • Widgets : This is just Social Sign Row, Because In UI we have Common Google and Facebook SignIN Icons.


Codes

FirebaseController.dart

In below code We have

_auth : that will help us in creating and user login.

firebaseUser : which will help user to keep user logged in into the app whenever user re-open flutter app.

then we have
3 method that will help us in Creating account in Firebase auth, Login in using Firebase auth and signOut the user from app.

import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter_login_ui/Screen/Dashboard.dart';
import 'package:flutter_login_ui/Screen/LoginPage.dart';
import 'package:get/get.dart';
import 'package:cloud_firestore/cloud_firestore.dart';


class FirebaseController extends GetxController{
   
  FirebaseAuth _auth = FirebaseAuth.instance;

  Rx<User> _firebaseUser = Rx<User>();

  String get user => _firebaseUser.value?.email;

  @override
  void onInit() {
    _firebaseUser.bindStream(_auth.authStateChanges());
  }


  // function to createuser, login and sign out user

 void createUser(String firstname,String lastname,String email,String password) async
 {
   CollectionReference reference = FirebaseFirestore.instance.collection("Users");

   Map<String,String> userdata ={
     "First Name": firstname,
      "Last Name": lastname,
      "Email":email
   };
   
   await _auth.createUserWithEmailAndPassword(email: email, password: password).
   then((value) {

     reference.add(userdata).then((value) =>  Get.offAll(LoginPage()));
   }).catchError((onError)=>
       Get.snackbar("Error while creating account ", onError.message),
   );
 }

 void login(String email,String password) async
 {
   await _auth.signInWithEmailAndPassword(email: email, password: password).then((value) => Get.offAll(Dashboard())).
       catchError((onError)=>
   Get.snackbar("Error while sign in ", onError.message));
 }

 void signout() async{
 await _auth.signOut().then((value) => Get.offAll(LoginPage()));
 }
}

LoginPage.dart

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/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:velocity_x/velocity_x.dart';

class LoginPage extends GetWidget<FirebaseController> {

  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: (){
                          print("Login Clicked Event");
                          _login();
                        },
                        child: "Login".text.white.light.xl.makeCentered().box.white.shadowOutline(outlineColor: Colors.grey).color(Color(0XFFFF0772)).roundedLg.make().w(150).h(40)),
                    HeightBox(20),
                    "Login with".text.white.makeCentered(),
                    SocialSignWidgetRow()

                  ],
                ),
              )
            ],
          ),
        ),
        bottomNavigationBar: GestureDetector(
          onTap: (){
            Navigator.pushReplacement(context, MaterialPageRoute(builder: (context)=>RegistrationPage()));
          },
          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() {

    controller.login(email.text, pass.text);
  }

}




RegistrationPage.dart

import 'dart:math';

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 'file:///C:/Android%20Studio%20Stuff/Flutter%20Project/flutter_login_ui/lib/Screen/LoginPage.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:velocity_x/velocity_x.dart';
import 'package:get/get.dart';

class RegistrationPage extends GetWidget<FirebaseController>{
  final TextEditingController firstn = TextEditingController();
  final TextEditingController lastn = TextEditingController();
  final TextEditingController email = TextEditingController();
  final TextEditingController password = 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: 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: RegisterUser,
                          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),
                      "Login with".text.black.makeCentered(),

                     SocialSignWidgetRow()

                    ],
                  ),
                ),
              )
            ],
          ),
        ),
        bottomNavigationBar: GestureDetector(
          onTap: (){
            Navigator.pushReplacement(context, MaterialPageRoute(builder: (context)=>LoginPage()));
          },
          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),
        )
    );
  }
  void RegisterUser() {

     controller.createUser(firstn.text, lastn.text, email.text, password.text);

  }
}


Dashboard.dart

import 'package:flutter/material.dart';
import 'package:flutter_login_ui/GetXHelper/FirebaseController.dart';

import 'package:get/get.dart';

class Dashboard extends GetWidget<FirebaseController> {


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            RaisedButton(onPressed: (){
             //logout
              controller.signout();
            },child: Text("Sign Out"),)
          ],
        ),
      ),
    );
  }
}

SocialSignWidgetRow.dart

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

class SocialSignWidgetRow extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      children: [

        Container(
          width: 30,
          height: 30,
          child: SvgPicture.asset("images/assets/google.svg"),
        ),
        Container(
          width: 30,
          height: 30,
          child: SvgPicture.asset("images/assets/facebook.svg"),
        ),
      ],
    );
  }
}

InstanceBinding.dart

import 'package:get/get.dart';
import 'GetXHelper/FirebaseController.dart';

class InstanceBinding extends Bindings{
  @override
  void dependencies() {
    // TODO: implement dependencies
    Get.lazyPut<FirebaseController>(() => FirebaseController());
  }

}

IsSignedIN.dart

import 'GetXHelper/FirebaseController.dart';
import 'package:get/get.dart';
import 'package:flutter/material.dart';
import 'Screen/LoginPage.dart';
import 'Screen/Dashboard.dart';

class IsSignedIn extends GetWidget<FirebaseController> {
  @override
  Widget build(BuildContext context) {
    return Obx((){
       return Get.find<FirebaseController>().user!=null ? Dashboard() : LoginPage();
    });
  }
}

main.dart

import 'package:flutter/material.dart';
import 'package:flutter_login_ui/Screen/Dashboard.dart';
import 'package:flutter_login_ui/Screen/LoginPage.dart';
import 'package:flutter_login_ui/Screen/RegistrationPage.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter_login_ui/WelcomePage.dart';
import 'package:flutter_login_ui/isSignedIn.dart';
import 'package:get/get.dart';

import 'InstanceBinding.dart';


void main() async{
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(MyApp());
}

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

  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      initialBinding: InstanceBinding(),
      title: 'Flutter Demo',
      debugShowCheckedModeBanner: false,
      home: IsSignedIn(),
      routes: {
        '/welcome':(context) => WelcomePage(),
        '/login':(context)=> LoginPage(),
        '/reg':(context)=>RegistrationPage(),
        '/dashboard':(context)=>Dashboard(),
      },
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),


    );
  }
}

And We are done your flutter app is now connected with firebase and provides Flutter Firebase auth with Getx and also store user register data to firebase database.

 

Comments are closed.