简体   繁体   中英

NoSuchMethodError: The method '[]' was called on null. (Flutter)

I am running my Flutter app and getting this error:

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

This is My User Class:-

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'],

    );
  }
}

The Document in the database isn't null, What Could Be Causing This Problem ??

Try this one

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM