Flutter social authentication with Firebase

Posted By : Saurabh Singh | 30-Sep-2022

About flutter:

Flutter is an open-source UI software development kit (SDK) that was primarily created by Google. It is used to develop cross-platform applications for Android, iOS, Linux, macOS, Windows, and the web from a single codebase. 

We will discuss how we can implement firebase authentication in our app. Mostly firebase is used for push notifications but we will discuss how we can also use it for multiple purposes like social authentication and web hosting etc.

Table of Content:

1) Introduction of Firebase.

2) Implementation of code.

 

1) Introduction of Firebase

 

Firebase is a set of hosting services for any type of application. It offers NoSQL and real-time hosting of database, content, social authentication, and notification, or services, such as a real-time communicating server.

2)Creating a new project

2.1) create a new flutter project.

2.2) open new pubspec.yaml file and install plugin(required).

2.2.1)firebase_auth.

2.2.2)firebase_core.

2.2.3)cloud_firebase.

2.2.4)google_sign_in.

2.2.5)flutter_facebook_auth.

2.2.6)get_x.// for state management

Now you need to visit firebase console window and need to create your project and add your Package name with other details. Firebase will help you to setup project.

Now you need to open your permission and user and add SHA! Key to project.

Implementation of code:

Main.dart code

import 'package:firebase_core/firebase_core.dart';

import 'package:flutter/foundation.dart';

import 'package:flutter/material.dart';

import 'package:flutter/services.dart';

import 'package:get/get.dart';

import 'dart:async';

void main() async {

  WidgetsFlutterBinding.ensureInitialized();

 

await Firebase.initializeApp(

 

   options: FirebaseOptions(

     apiKey: "", /// you will find these details on firebase console under your project user and permission

     appId: "",

     projectId: "",

     messagingSenderId: '',

   ),

);

 

  SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(

    statusBarColor: Colors.transparent, // status bar color

  ));

  SystemChrome.setPreferredOrientations([

    DeviceOrientation.portraitUp,

  ]);

  runApp(const MyApp());

}

 

class MyApp extends StatelessWidget {

  const MyApp({Key? key}) : super(key: key);

// This widget is the root of your application.

  @override

  Widget build(BuildContext context) {

    return GetMaterialApp(

      title: 'Flutter Demo',

      theme: ThemeData(

   primarySwatch: Colors.blue,

      ),

      home:  WelcomeScreen(),

    );

  }

}

 

 

 

 

Controller.dart code

import 'package:cloud_firestore/cloud_firestore.dart';

import 'package:edtech/model/user_model.dart';

import 'package:edtech/views/authentication_views/login.dart';

import 'package:edtech/views/home_views/HomePage.dart';

import 'package:firebase_auth/firebase_auth.dart';

import 'package:flutter_facebook_auth/flutter_facebook_auth.dart';

import 'package:get/get.dart';

import 'package:get_storage/get_storage.dart';

import 'package:google_sign_in/google_sign_in.dart';

 

 

class UserController extends GetxController{

  var dataStroage= GetStorage();

  final FirebaseAuth _auth = FirebaseAuth.instance;

  final FirebaseFirestore firebaseFirestore = FirebaseFirestore.instance;

  //late final SharedPreferences pref;

  final userRef = FirebaseFirestore.instance

      .collection('users')

      .withConverter<UserModel>(

    fromFirestore: (snapshot, _) => UserModel.fromJson(snapshot.data()!),

    toFirestore: (user, _) => user.toJson(),

  );

  UserModel? user;

 

// late String user ;

  @override

  void onInit() {

    // TODO: implement onInit

    initData();

    super.onInit();

  }

  initData()async{

    //  pref = await SharedPreferences.getInstance();

    //getUser();

  }

 

  initialNavigate() async{

    await Future.delayed(Duration(seconds: 3));

    if(dataStroage.read('firsttimeopen')??true){

      Get.toNamed('/onboarding');

    }else{

    navigatorUser();

    }

  }

  navigatorUser(){

    final String? Token=dataStroage.read("authToken");

    final String? usertype=dataStroage.read("usertype");

    if(Token==null){

      Get.offAndToNamed('/welcomescreen');

  } else{

      Get.offAndToNamed('/login');

    }

  }

  void doneIntro(){

    dataStroage.write("firsttimeopen", false);

    //  pref.setBool('firstopen', false);

    //navigatorUser();

    navigateUser();

  }

  ///Navigate the user according to their state

  void navigateUser() {

    if (_auth.currentUser != null) {

      if (_auth.currentUser!.phoneNumber != null) {

        Get.to(()=>HomePage());

      } else {

        Get.to(()=>HomePage());

       // Get.toNamed(Routes.REGISTRATION);

      }

    } else {

      Get.to(()=>LoginPage());

    }

  }

 

  ///get the user data and store in user

  Future<void> getUser() async {

    if (_auth.currentUser != null) {

      await userRef.doc(_auth.currentUser!.uid).get().then((value) {

        if (value.data() != null) {

          user = value.data()!;

          update();

        }

      });

    }

  }

 

  ///Logout the user

  Future<void> logout() async {

    await _auth.signOut();

    GoogleSignIn().signOut();

    FacebookAuth.instance.logOut();

    navigateUser();

  }

 

  ///Sign Up with google

  void signInWithGoogle() async {

    final GoogleSignInAccount? googleUser = await GoogleSignIn().signIn();

    final GoogleSignInAuthentication googleAuth =

    await googleUser!.authentication;

 

    final credential = GoogleAuthProvider.credential(

      accessToken: googleAuth.accessToken,

      idToken: googleAuth.idToken,

    );

    UserCredential userCredential =

    await FirebaseAuth.instance.signInWithCredential(credential);

    print(userCredential);

    if (userCredential.additionalUserInfo!.isNewUser) {

      FirebaseFirestore.instance

          .collection('users')

          .doc(_auth.currentUser!.uid)

          .set({

        'firstName': userCredential.additionalUserInfo!.profile!['given_name'],

        'lastName': userCredential.additionalUserInfo!.profile!['family_name'],

        'email': userCredential.user!.email,

        'phoneVerified': false,

        'imageUrl': userCredential.user!.photoURL,

      }).then((value) {

        getUser();

        Get.to(()=>HomePage());

      });

    } else {

      await getUser();

      navigateUser();

    }

  }

 

  ///Sign up with facebook

  void signInWithFacebook() async {

    final LoginResult loginResult = await FacebookAuth.instance.login();

    final result = loginResult.accessToken!.token;

    final OAuthCredential facebookAuthCredential =

    FacebookAuthProvider.credential(result);

 

    await FirebaseAuth.instance

        .signInWithCredential(facebookAuthCredential)

        .then((userCredential) async {

      if (userCredential.additionalUserInfo!.isNewUser) {

        FirebaseFirestore.instance

            .collection('users')

            .doc(_auth.currentUser!.uid)

            .set({

          'firstName':

          userCredential.additionalUserInfo!.profile!['first_name'],

          'lastName': userCredential.additionalUserInfo!.profile!['last_name'],

          'email': userCredential.user!.email,

          'phoneVerified': false,

          'imageUrl': userCredential.user!.photoURL,

        }).then((value) async {

          await getUser();

          navigateUser();

        });

      } else {

        await getUser();

        navigateUser();

      }

    }, onError: (error) {

      // getErrorSnackBar('Error', error.toString());

    });

  }

 

 

 

}

 

 

 

WelcomeScreen.dart code

import 'package:flutter/gestures.dart';

import 'package:flutter/material.dart';

import 'package:get/get.dart';

 

class WelcomeScreen extends StatelessWidget {

  const WelcomeScreen({Key? key}) : super(key: key);

   

  UserController user=Get.put(UserController());

  @override

  Widget build(BuildContext context) {

    return Scaffold(

      backgroundColor: kblack,

      body: SafeArea(

        child: SingleChildScrollView(

          child: Padding(

            padding: const EdgeInsets.symmetric(horizontal: 28.0),

            child: Column(

              

              children: [

                SizedBox(height: 175,),

                Image.asset(

                  logoImage,

 

                ),

                SizedBox(height: 177,),

                GestureDetector(

                  onTap: (){

                    User.signInWithGoogle();

                  },

                  child: Container(

                    padding: EdgeInsets.all(8),

                    decoration: BoxDecoration(

                    borderRadius: BorderRadius.circular(5),

                     color: khintBlack

                    ),

                    child: Row(

                      children: [

                        Icon(Icons.email_outlined,color: kwhitecolor,),

                        SizedBox(

                          width: 10,

                        ),

                        Text("Signin with google),

 

                      ],

                    ),

                  ),

                ),

                SizedBox(height: 20,),

                GestureDetector(

                  onTap: (){

                    User.signInWithFacebook();

                  },

                  child: Container(

                    padding: EdgeInsets.all(8),

                    decoration: BoxDecoration(

                      borderRadius: BorderRadius.circular(5),

                        color: khintBlack

                    ),

 

                    child: Row(

                      children: [

                        Icon(Icons.email,color: kwhitecolor,),

                        SizedBox(

                          width: 10,

                        ),

                        Text("Signin with Facebook),

 

                      ],

                    ),

                  ),

                ),

 

                Container(

                  child: Padding(

                    padding: const EdgeInsets.symmetric(horizontal: 28.0,vertical: 28),

                    child: Row(

                      mainAxisAlignment: MainAxisAlignment.center,

                      children: [

                        Expanded(

                          child: RichText(

                            maxLines: 3,

                            text: TextSpan(

                              children: [

                                const TextSpan(

                                  text:

                                  "By continuing you agree to the",

                                  style: KBody10khintBlack600,),

                                TextSpan(

                                    text: " Terms of services ",

                                    style: KBody10white600,

                                    recognizer: TapGestureRecognizer()

                                      ..onTap = () {

                                        // //  where you want to send

                                      }),

                                const TextSpan(

                                  text: " and ",

                                  style: KBody10khintBlack600,

                                ),

                                TextSpan(

                                    text: " Privacy Policy",

                                    style: KBody10white600,

                                    recognizer: TapGestureRecognizer()

                                      ..onTap = () {

                                        //  where you want to send

                                      }),

                              ],

                            ),

                          ),

                        ),

                      ],

                    ),

                  ),

                ),

              ],

            ),

          ),

        ),

      ),

    );

  }

}

 

 

/// logout code also have been writen to logout user under controller.dart

 

 

 

 

 

 

 

 

 

 

About Author

Author Image
Saurabh Singh

Saurabh is working as a Mobile Application Developer with an overall 2+ years of experience. His areas of expertise are Flutter and Android Development. He is a detail-oriented person with good problem-solving skills.

Request for Proposal

Name is required

Comment is required

Sending message..