check authentication state of User using FirebaseAuth in Flutter

1,733

isUserLoggedIn() isn't returning a stream of any kind. I recommend just listening to the actual authStateChanges() stream.

  Widget build(BuildContext context) {
    return StreamBuilder<User>(
      stream: FirebaseAuth.instance.authStateChanges(),
      builder: (BuildContext context, AsyncSnapshot<User> snapshot) { 
        if(snapshot.hasData) {
          print("data exists");
          return First();
        }
        else {
          return SignIn();
        }
      },
    );
  }
Share:
1,733
Shlok Jain
Author by

Shlok Jain

Updated on December 23, 2022

Comments

  • Shlok Jain
    Shlok Jain over 1 year

    I know a question like this exists but it is filled with outdated and incorrect answers. The new FlutterFire docs use Streams to get the state of the User and I had a hard time, trying to perform such a trivial task because I am inexperienced with Flutter and Dart. Here is the answer and ref of the outdated question.

    I am expecting an answer along with StreamBuilder, and here is the code I have written up till now:

    @override
      Widget build(BuildContext context) {
        return StreamBuilder(
          builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) { 
            if(snapshot.hasData) {
              print("data exists");
              return snapshot.data ? First() : SignIn();
            }
            else {
              return SignIn();
            }
          },
          future: isUserLoggedIn(),
        );
      }
    
    Stream<bool> isUserLoggedIn() {
        FirebaseAuth.instance
            .authStateChanges()
            .listen((User user) {
          if (user == null) {
            print('User is currently signed out!');
            // return false; ???
          } else {
            print('User is signed in!');
            // return true; ???
          }
        });
      }
    

    EDIT:

    Firebase Auth enables you to subscribe in realtime to this state via a >Stream. Once called, the stream provides an immediate event of the user's >current authentication state, and then provides subsequent events whenever ?the authentication state changes.

    FlutterFire Auth Doc