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.