【问题标题】:How to fix "The method 'containsKey' can't be unconditionally invoked because the receiver can be 'null'." in Null Safety?如何解决“无法无条件调用方法'containsKey',因为接收者可以为'null'。”在零安全?
【发布时间】:2021-09-05 11:14:21
【问题描述】:

我正在将我的应用程序迁移到 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;

}

【问题讨论】:

  • 顺便问一下,你使用的是哪个版本的 firebase 包?

标签: flutter dart-null-safety


【解决方案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) {

【讨论】:

  • 感谢您的回答mightybruno,但现在我得到了The method 'containsKey' isn't defined for the type 'Object'.。我正在使用cloud_firestore: ^2.2.2
猜你喜欢
  • 2021-09-18
  • 1970-01-01
  • 2023-03-05
  • 1970-01-01
  • 2021-10-05
  • 1970-01-01
  • 2021-08-10
  • 1970-01-01
  • 2021-06-02
相关资源
最近更新 更多