【问题标题】:NoSuchMethodError: The method '[]' was called on null. (Flutter)NoSuchMethodError:在 null 上调用了方法“[]”。 (扑)
【发布时间】:2021-09-22 01:14:51
【问题描述】:

我正在运行我的 Flutter 应用程序并收到此错误:

The method '[]' was called on null.
Receiver: null
Tried calling: []("id")

这是我的用户类:-

class User {

final String id;
final String username;
final String email;
final String photoUrl;


User({
  this.id,
  this.username,
  this.email,
  this.photoUrl,
});

 factory User.fromDocument(DocumentSnapshot doc) {
   return User(
    id: doc.data()['id'],
    username: doc.data()['username'],
    email: doc.data()['email'],
    photoUrl: doc.data()['photoUrl'],

    );
  }
}

数据库中的文档不为空, 什么可能导致这个问题??

【问题讨论】:

  • 您在代码执行期间是否尝试打印doc.data()

标签: firebase flutter google-cloud-firestore


【解决方案1】:

试试这个

 factory User.fromDocument(DocumentSnapshot doc) {
   if(doc.data() == null){
      return User();
   }
   return User(
    id: doc.data()['id'],
    username: doc.data()['username'],
    email: doc.data()['email'],
    photoUrl: doc.data()['photoUrl'],
    );
  }

【讨论】:

  • 不,它不起作用我只是收到错误“未为类型 'Map Function()' 定义运算符'[]'。尝试定义运算符'[]'。“
  • @SaiPrashanth 我更新了我的答案,原因可能是 DocumentSnapshot 是null
  • 它有效但我必须将 doc == null 编辑为 doc.data() == null
猜你喜欢
  • 2021-11-15
  • 2020-05-23
  • 1970-01-01
  • 2021-01-19
  • 1970-01-01
  • 2021-11-30
  • 2021-03-11
  • 2021-09-29
  • 2021-06-18
相关资源
最近更新 更多