How to fix "The method 'containsKey' can't be unconditionally invoked because the receiver can be 'null'." in Null Safety?

Issue

I am migrating my app to Null Safety and learning the new approaches, but I got stuck with "The method ‘containsKey’ can’t be unconditionally invoked because the receiver can be ‘null’." when checking if a field exists on firebase or not with containsKey(). Do you guys have any idea on how to check it?

class AuthUser {
  AuthUser(
     {this.id,
      this.displayName,
      this.bio,
      this.photoUrl,
      required this.email,
      this.cpf,
      this.isBlocked = false,
      this.type,
      this.timestamp,
      required this.password});

AuthUser.fromDocument(DocumentSnapshot doc) {
   id = doc['id'];
   email = doc['email'];
   isBlocked = doc['isblocked'] as bool;
   displayName = doc['displayName'];
   if (doc.data().containsKey('cpf')) { //this is the checking I used before but with null safety containsKey seems to not be the approach anymore
      cpf = doc['cpf'];
   }
   if (doc['phone'] != null) {
      phone = doc['phone'];
   }

   bio = doc['bio'];
   photoUrl = doc['photoUrl'];
   type = doc['type'];
   timestamp = doc['timestamp'];
   if (doc['address'] != null) {
     address = Address.fromMap(doc['address'] as Map<String, dynamic>);
  }
 }

String? id;
String? displayName;
String? bio;
String? photoUrl;
late String email;
String? phone;
String? type;
late String password;
String? cpf;
Timestamp? timestamp;

}

Solution

If you’re sure the data can’t be null, simply add a null assertion operator like following:

   if (doc.data()!.containsKey('cpf')) {
      cpf = doc['cpf'];
   }

https://pub.dev/documentation/cloud_firestore/latest/cloud_firestore/DocumentSnapshot-class.html


Also, to get rid of the type error (the one from your comment), add a type parameter to this line:

AuthUser.fromDocument(DocumentSnapshot doc) {

I’m not sure what type should it have, but looking at the method you’re calling right after, I assume it will be a map:

AuthUser.fromDocument(DocumentSnapshot<Map<String, dynamic>> doc) {

Answered By – eeqk

Answer Checked By – Mary Flores (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.