Search code examples
firebaseflutterdartfirebase-authenticationstream-builder

Firebase Auth not saving current user


In my app I'm trying to perform a simple login/signup operation.

I have a StreamBuilder that returns a Login Screen if there is no user, and a home screen if a user is logged in:

StreamBuilder(
          stream: FirebaseAuth.instance.onAuthStateChanged,
          builder: (BuildContext context, AsyncSnapshot snapshot) {
            Widget widget;
            switch (snapshot.data) {
              case (null):
                widget = SignIn();
                break;
              default:
                widget = Home();
            }

            return AnimatedSwitcher(
          child: widget,
          duration: Duration(seconds: 1),
          transitionBuilder: (Widget child, Animation<double> animation) {
            return ScaleTransition(child: child, scale: animation);
          },
        );
          }),

The code works perfectly as shown below:

Simple Login

But when a user is already signed in, and I close and reopen the app, the login page shows briefly before it redirects to the home page.

The same happens when I click on hot restart:

Hot Restart

In the image above, I was already signed in, then I clicked hot reload and the login screen showed briefly before I was redirected to the home screen.

The same happens when the internet is turned off, and there is no animated switcher.

How can I fix this problem?


Solution

  • use ConnectionState:

    if (snapshot.connectionState == ConnectionState.waiting) {
     return Container();
    }
    
    

    You can replace Container with a SplashScreen/Loading Screen