Home > Software engineering >  The operator '[]' isn't defined for the type 'Object? Function()'. (Documen
The operator '[]' isn't defined for the type 'Object? Function()'. (Documen

Time:04-19

  //user data from snapshot
  UserData _userDataFromSnapshot(DocumentSnapshot snapshot){
    return UserData (
      uid: uid,
      car: snapshot.data['car'], //problem
      num: snapshot.data['phone'], //problem
      name: snapshot.data['name'], //problem

    );
  }

Im not sure why it shows the problem of "The operator '[]' isn't defined for the type 'Object? Function()'." please help I'm still new to flutter

CodePudding user response:

You need to add parenthesis:

UserData _userDataFromSnapshot(DocumentSnapshot snapshot){
    var data = snapshot.data()!;
    return UserData (
      uid: uid,
      car: data['car'], //problem
      num: data['phone'], //problem
      name: data['name'], //problem

    );
  }

See https://firebase.flutter.dev/docs/firestore/usage/#realtime-changes

CodePudding user response:

You cannot access snapshot.data['car'] like this because snapshot.data() return Object, so you need to cast it to Map<String, dynamic>

UserData _userDataFromSnapshot(DocumentSnapshot snapshot){
Map<String, dynamic> data = snapshot.data() as Map<String, dynamic>;
    return UserData (
      uid: uid,
      car: data['car'],
      num: data['phone'],
      name: data['name'],

    );
  }
  • Related