Reputation: 44
I am using Firebase authentication method to get detail info of the signed in user (i.e. displayname and photourl). My code is as follow:
final user = FirebaseAuth.instance.currentUser!;
After succesfully signed in, I signed out to return to the login screen. However, when I tried to sign in again, I got an error referring to the code above: "Null operator used on null value."
Any sugestion on the problem?
Upvotes: 0
Views: 1363
Reputation: 421
You have to listen to the auth state changes. Add this method to your Authentication class.
Future<void> initializeUser(BuildContext context) async {
FirebaseAuth.instance.authStateChanges().listen(
(User? user) async {
if (user == null) {
print('user is signed out');
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const LoginScreen(),
),
);
} else {
await fetchUserData(); // handle fetching user data
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const MyHomePage(),
),
);
print('user has signed in');
}
},
);
}
Upvotes: 2