如何修复 Null Safety 中的 "The method 'containsKey' can't be unconditionally invoked because the receiver can be 'null'."?

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

我正在将我的应用程序迁移到 Null Safety 并学习新方法,但我遇到了“无法无条件调用方法 'containsKey' 因为接收器可以是 'null'”。当使用 containsKey() 检查字段是否存在于 firebase 上时。你们知道如何检查吗?

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;

}

如果您确定数据不能为空,只需添加一个空断言运算符,如下所示:

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

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


此外,要消除类型错误(您评论中的错误),请向此行添加一个类型参数:

AuthUser.fromDocument(DocumentSnapshot doc) {

我不确定它应该是什么类型,但看看你之后调用的方法,我认为它是一个映射:

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