The official docs for Firebase Authentication for Flutter mentions this code to check whether user is logged in or not:
FirebaseAuth.instance
.authStateChanges()
.listen((User user) {
if (user == null) {
print('User is currently signed out!');
} else {
print('User is signed in!');
}
});
Docs also mention that Firebase must be initialized before anything else so I have added the initialization code to main.dart
:
class MyApp extends StatelessWidget {
final Future<FirebaseApp> _initialization = Firebase.initializeApp();
@override
Widget build(BuildContext context) {
return FutureBuilder(
future: _initialization,
builder: (context, snapshot) {
if (snapshot.hasError) {
// Handle error
}
if (snapshot.connectionState == ConnectionState.done) {
return AuthState();
}
return CircularProgressIndicator();
},
);
}
}
AuthState
is where I want to manage the authentication state. I have added it in the same file.
class AuthState extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Auth',
home: FirebaseAuth.instance.authStateChanges().listen((User user) {
if (user == null) {
return SignupScreen();
} else {
return HomeScreen();
}
}),
);
}
}
The above code does not work because home
expects a widget and authStateChanges
returns StreamSubscription
so how to make it work? I want to redirect to signup screen if user is not authenticated and to the home screen if user is.