How to Implement Firebase Login With Flutter Using onAuthStateChanged ?

· 3 min read
How to Implement Firebase Login With Flutter Using onAuthStateChanged
How to Implement Firebase Login With Flutter Using onAuthStateChanged

When we implement firebase authentication we always use the onAuthStateChanged listener provided by firebase to determine if the user is logged in or not and respond accordingly. So in this article, we will go through How to Implement Firebase Login With Flutter Using onAuthStateChanged?

How to Implement Firebase Login With Flutter Using onAuthStateChanged ??

Firebase returns a Stream of FirebaseUser with its onAuthStateChanged function. There are many ways to listen to the user’s authentication state change. Take a look at below Code Snippet.

  • We return a StreamBuilder to my App’s home page, and the StreamBuilder returns specific pages based on the auth status of the user.
    @override
    Widget build(BuildContext context) {
      return MaterialApp(
          title: 'Your App Name',
          home: _getLandingPage()
      );
    }
    
    Widget _getLandingPage() {
      return StreamBuilder<FirebaseUser>(
        stream: FirebaseAuth.instance.onAuthStateChanged,
        builder: (BuildContext context, snapshot) {
          if (snapshot.hasData) {
            if (snapshot.data.providerData.length == 1) { // logged in using email and password
              return snapshot.data.isEmailVerified
                  ? MainPage()
                  : VerifyEmailPage(user: snapshot.data);
            } else { // logged in using other providers
              return MainPage();
            }
          } else {
            return LoginPage();
          }
        },
      );
    }
  • Users can also set the Firebase instance initState(). Code Snippet will look like the below:
    @override
    void initState() {
      super.initState();
      FirebaseAuth.instance.onAuthStateChanged.listen((firebaseUser) {
        // do whatever you want based on the firebaseUser state
      });
    }

    Users can also create a stream as a getter for the onAuthStateChanged inside an AuthService class. To help you manage the state, you can use the Provider package. The AuthService class will extend the ChangeNotifier class.

    class AuthService extends ChangeNotifier {
        final FirebaseAuth _auth = FirebaseAuth.instance;
        final GoogleSignIn _googleSignIn = new GoogleSignIn();
        // create a getter stream
        Stream<FirebaseUser> get onAuthStateChanged => _auth.onAuthStateChanged;
        //Sign in async functions here ..
    
    }

    Now the user needs to wrap your MaterialApp with ChangeNotifierProvider and return an instance of the AuthService class in creating a method like so:

    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return ChangeNotifierProvider(
          create: (context) => AuthService(),
          child: new MaterialApp(
          title: 'Firebase Auth Demo',
          home: Landing(),
          ),
        );
      }
    }

Conclusion:

Thanks for Reading !!! Keep Fluttering !!!

In this article, We have walked through How to Implement Firebase Login With Flutter Using onAuthStateChanged?

Do Share us valuable Feedback to Serve You Better.

FlutterAgency.com is our portal Platform dedicated to Flutter Technology and Flutter Developers. The portal is full of cool resources from Flutter like Flutter Widget GuideFlutter ProjectsCode libs and etc.

FlutterAgency.com is one of the most popular online portal dedicated to Flutter Technology and daily thousands of unique visitors come to this portal to enhance their knowledge on Flutter.

Leave a Reply