How to fix _CastError (Null check operator used on a null value) -Flutter (Dart)

Advertisements

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.

>Solution :

Because currentUser is null, you need to accept null and handle it properly like.

final user = FirebaseAuth.instance.currentUser;
// now `user` can accept null and the title error will be gone

Next thing comes when you are using it.

if(user?.photoURL!=null) CircleAvatar(....

Find more about null-safety.

Leave a ReplyCancel reply