NoSuchMethodError: 在 null 上调用了方法“[]”。 (颤抖)

时间:2021-07-12 23:02:08

标签: firebase flutter google-cloud-firestore

我正在运行我的 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'],

    );
  }
}

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

1 个答案:

答案 0 :(得分:0)

试试这个

 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'],
    );
  }