Home > Blockchain >  Flutter The method '[]' can't be unconditionally invoked because the receiver can be
Flutter The method '[]' can't be unconditionally invoked because the receiver can be

Time:06-21

im having an error stating "The method '[]' can't be unconditionally invoked because the receiver can be 'null'. Try making the call conditional (using '?.') or adding a null check to the target ('!')." Ive tried to add the '!' mark as stated and searching online but it doesn't resolve the issue. any ideas?

factory UserModel.fromSnapshot(DocumentSnapshot snapshot) {
    return UserModel(
      name: snapshot.data()["name"],
      email: snapshot.data()['email'],
      phoneNumber: snapshot.data()['phoneNumber'],
      uid: snapshot.data()['uid'],
      isOnline: snapshot.data()['isOnline'],
      profileUrl: snapshot.data()['profileUrl'],
      status: snapshot.data()['status'],
      designation: snapshot.data()['designation'],
      company: snapshot.data()['company'],
    );
  }

CodePudding user response:

That's because if snapshot.data() is null then you can't really access its fields, try null checking it :

snapshot.data()?['name'] ?? ''

CodePudding user response:

Can you try like this

factory UserModel.fromSnapshot(DocumentSnapshot snapshot) {
    return UserModel(
      name: snapshot.data()["name"] ?? "",
      email: snapshot.data()['email'] ?? "",
      phoneNumber: snapshot.data()['phoneNumber'] ?? 0,
      uid: snapshot.data()['uid'] ?? 0,
      isOnline: snapshot.data()['isOnline'] ?? false,
      profileUrl: snapshot.data()['profileUrl'] ?? ""
    );
  }
  • Related