I am new in Flutter and trying to learn Firebase. In the given below code,I am trying to get data of currentUser that is logged in. But I get _CastError (Null check operator used on a null value). I tried to solve it but couldn’t accomplished it. How can I solve it?
class HomeScreen extends StatefulWidget {
const HomeScreen({super.key});
@override
State<HomeScreen> createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
@override
Widget build(BuildContext context) {
final user = FirebaseAuth.instance.currentUser!;
var useremail = "Error";
if (user.email != null) { //********Problem occurs here**********
var useremail = user.email;
}
print("$user");
return Scaffold(
appBar: AppBar(
title: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text("HomeScreen"),
],
)),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(useremail),
ElevatedButton(
onPressed: () {
FirebaseAuth.instance.signOut();
Navigator.of(context).push(MaterialPageRoute(
builder: (context) => MyHomePage(),
));
},
child: Text("Sign Out")),
],
),
));
}
}
```
2
Answers
In addition to checking that user.email != null , also verify that the user object is not null.
Replace the above block of code by this:
The problem is that you gave an exclamation after FirebaseAuth.instance.currentUser, that stated that the user can’t be null.
Also, don’t forget to check if user is null or not before signing him out.
To learn more about null safety, visit: https://dart.dev/null-safety