简体   繁体   中英

check authentication state of User using FirebaseAuth in Flutter

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

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();
        }
      },
    );
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM