I am trying to get the user’s profile picture, name and email but I keep on getting the _CastError (Null check operator used on a null value)
error. This is where I get my error:
final user = FirebaseAuth.instance.currentUser!;//at the end is where the error is (the '!')
Code:
Column(
children: [
CircleAvatar(
radius: 52,
backgroundImage: NetworkImage(user.photoURL!),
),
const SizedBox(
height: 8,
),
Text(
user.displayName!,
style: titleStyle,
),
const SizedBox(
height: 8,
),
Text(
user.email!,
style: titleStyle,
),
],
),
I’ve tried moving the !
around but it just throws the error somewhere else then. I’ve tried implementing ??/?
on some places but to also no help.
3
Answers
Because
currentUser
is null, you need to accept null and handle it properly like.Next thing comes when you are using it.
Find more about null-safety.
After watching some videos I figured that it was just a wrong approach and there are better and easier ways of doing it.
// 1. Check if the variable is null before using it:
if (variable != null) { // use variable safely } else { // handle null case }
// 2. Use the null-aware operator (
?.
) instead of the null check operator (!
) to avoid the error altogether:variable?.doSomething();
// 3. Use the null-coalescing operator (
??
) to provide a default value when the variable is null:final value = variable ?? defaultValue;