如何修复“无法无条件调用方法 'containsKey',因为接收器可以为 'null'。”在空安全?

时间:2021-06-21 19:34:14

标签: flutter dart-null-safety

我正在将我的应用程序迁移到 Null Safety 并学习新方法,但我遇到了“无法无条件调用‘containsKey’方法,因为接收器可以为‘null’”的问题。使用 firebase 检查字段是否存在于 containsKey() 时。你们有什么办法检查它吗?

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;

}

1 个答案:

答案 0 :(得分:1)

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

   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) {