check authentication state of User using FirebaseAuth in Flutter
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();
}
},
);
}
Shlok Jain
Updated on December 23, 2022Comments
-
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.
- Answer: https://stackoverflow.com/a/50714618/14080391
- Ref: https://firebase.flutter.dev/docs/auth/usage#authentication-state
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.