Flutter firebase auth doesn’t persist after app is killed

Since authStateChanges returns a Stream, you’ll want to use a StreamBuilder in your code to wrap that asynchronous operation too.

Something like this:

// once complete show your app
if (snapshot.connectionState == ConnectionState.done) {
  print('CONNECTED');
  return StreamBuilder(
    stream: FirebaseAuth.instance. authStateChanges(),
    builder: (BuildContext context, snapshot) {
      if (snapshot.hasData) {
        return MaterialApp(
          home: LoginPage(),
        );
      } else {
        return MaterialApp(
          home: HomePage(),
        );
      }
    }
  )
}

Unrelated: you’re repeated the code to create a MaterialApp quite frequently, which is not needed. For example, in the above snippet we could have only one mention of MaterialApp and get the same result with:

// once complete show your app
if (snapshot.connectionState == ConnectionState.done) {
  print('CONNECTED');
  return StreamBuilder(
    stream: FirebaseAuth.instance. authStateChanges(),
    builder: (BuildContext context, snapshot) {
      return MaterialApp(
        home: snapshot.hasData && snapshot.data != null ? HomePage() : LoginPage(),
      )
    }
  )
}

If you do this for all mentions of MaterialApp and other duplication, you can reduce the code significantly, making it less error prone and easier to maintain.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top