The operator '[]' isn't defined for the type 'Object'

Viewed 8594

I'm trying to get documents in brews collection from Firestore.

What is wrong with my code?

Help me somebody who is used to Flutter and Firebase.

////brew list from snapshot
List<Brew> _brewListFromSnapshot(QuerySnapshot snapshot) {
    return snapshot.docs.map((document) {
      return Brew(
        name: document.data()['name'] ?? '',
        strenght: document.data()['strength'] ?? 0,
        sugars: document.data()['sugars'] ?? '0',
      );
    }).toList();
  }

Attached screenshots regarding error:

2 Answers

According to the cloud_firestore plugin github:

/// A [DocumentSnapshot] contains data read from a document in your [FirebaseFirestore]
/// database.
///
/// The data can be extracted with the data property or by using subscript
/// syntax to access a specific field.

So perhaps this modification to your code would work:

List<Brew> _brewListFromSnapshot(QuerySnapshot snapshot) {
    return snapshot.docs.map((document) {
      return Brew(
        name: document['name'] ?? '',
        strength: document['strength'] ?? 0,
        sugars: document['sugars'] ?? '0',
      );
    }).toList();
  }

You're probably looking for document.data[] instead of document.data()[]

document.data is a getter that returns Map<String, dynamic>, so you'd just query it as document.data['someKey'] instead of document.data()['someKey']

So this code should work:

List<Brew> _brewListFromSnapshot(QuerySnapshot snapshot) {
    return snapshot.docs.map((document) {
      return Brew(
        name: document.data['name'] ?? '',
        strength: document.data['strength'] ?? 0,
        sugars: document.data['sugars'] ?? '0',
      );
    }).toList();
  }
Related