Implementing FirebaseAuthStateListener using Shared Prefrences in Flutter.

Written by vaibhavminiyar | Published 2018/04/29
Tech Story Tags: android | flutter | firebase | firebaseauthentication

TLDRvia the TL;DR App

Implementing FirebaseAuthStateListener using Shared Prefrences in Flutter.

Hello ✌️,

I started Flutter a month ago. I have built few small application in Flutter like Chat Application , Blog Application etc. I used Firebase for both the apps mentioned. One thing that I have realized while making blog application is about firebase auth state listener. In the flutter+firebase I didn’t find the Firebase Auth State listener as like in Android. (Auth state listener checks and continuously monitors the status of existence of the user and respectively shows the screen or activity in terms of Android)

So in order get the current status of user and show the respective Scaffold or Material App or any respective component in Flutter, I used “Shared Prefrences” library in Flutter

I have used Google Authenticatoin currently eith SharedPrefernce but one can use any of the Auth Method you want.

In Flutter Blog App I have Declared 2 Scaffolds viz. loginScaffold and homeScaffold. and Changed them with respect to Auth State.If user already Logged in then showing homeScaffold else showing loginScaffold. After that if Login happens successfully loginScaffold will be replaced by the homeScaffold.

Steps touse Shared Preference for Auth State Listening:

1. Adding Library to pubspec.yaml and importing in HomePage.dart

dependencies:flutter:sdk: flutter

cupertino_icons: ^0.1.0shared_preferences: "^0.4.0"...

Then importing into HomePage.dart as

import ‘package:shared_preferences/shared_preferences.dart’;

2. Create Instance of Shared Prefernce and checking Existance of value in same :

For the main screen I have used a material app whose “home :” attribute depends on current status of user that means if user is logged in it will show the homeScaffold and if not then will show loginScaffold.As Follows: (Code is Self Explantory :) )

class HomePage extends StatefulWidget {@overrideHomePageState createState() => new HomePageState();}

class HomePageState extends State<HomePage> {bool loggedIn = false; // this will check status

Future<Null> _function() async {

/\*\*  
This Function will be called every single time  
when application is opened and it will check   
if the value inside Shared Preference exist or not  
\*\*/

SharedPreferences prefs;  
prefs = **await** SharedPreferences._getInstance_();  
**this**.setState(() {  
  **if** (prefs.getString(**"username"**) != **null**) {  
    **loggedIn** \= **true**;  
  } **else** {  
    **loggedIn** \= **false**;  
  }  
});  

}. . . .

Scaffold homeScaffold = /*define as required*/;Scaffold loginScaffold = /*define as required*/;

@overrideWidget build(BuildContext context) {return new MaterialApp(title: "SimpleBlogApp",home: loggedIn ? homeScaffold : loginScaffold);}....

@overridevoid initState() {super.initState();this._function();....}}

3. When sign in is clicked _ensureLoggedIn() function/method will be called and if it is successful then storing their User ID, User Name, User Profile Image and User emailid inside the Shared preference and making loggedIn variable true:

Future<Null> _ensureLoggedIn() async {

SharedPreferences prefs;prefs = await SharedPreferences.getInstance();

........

//sign in the user here and if it is successful then do following

prefs.setString("username", user.displayName);prefs.setString("userid", user.id);prefs.setString("useremail", user.email);prefs.setString("userphotourl", user.photoUrl);this.setState(() {/*updating the value of loggedIn to true so it willautomatically trigger the screen to display homeScaffold.*/loggedIn = true;......});}

5. When user signs out clearing the Shared preference as:

Future<Null> logoutUser() async {//logout user SharedPreferences prefs;prefs = await SharedPreferences.getInstance();await googleSignIn.signOut();prefs.clear();prefs.commit();this.setState(() {/*updating the value of loggedIn to false so it willautomatically trigger the screen to display loginScaffold.*/loggedIn = false;});}

You can check the HomePage.dart file inside Flutter blog app project on the GitHub. The code is taken from that file only.

For more Flutter project by me take a look at my GitHub Profile .

Happy Coding 😍Thanks✌️🙂


Published by HackerNoon on 2018/04/29