Search code examples
fluttersessionfirebase-authenticationsharedpreferences

Flutter: How to keep user logged-in even when app is closed using Firebase Auth


I'm using Firebase Auth in my Flutter App. User is authenticated and logged in using 'Auth' but when app is closed/cleared from mobile memory, the user is automatically signed out.

How can I keep the user signed-in and have their state/session active even when the App is closed.

Explored similar questions but no satisfied answer was found.

Any help would be appreciated. Thanks!


Solution

  • FirebaseAuth has this stream called authStateChanges, which checks the user is present or not. And we can use this stream in Streambuilder:

    return MaterialApp(
        home: StreamBuilder(
          stream: FirebaseAuth.instance.authStateChanges(),
          builder: (context, snapshot) {
            if (snapshot.hasData) {
              return HomePage();
            }
            if (snapshot.hasError) {
              return Scaffold(body: Text(snapshot.error.toString()));
            }
            return SignInPage();
          },
        ),
      );