首页 > 解决方案 > 未为类型“对象”定义运算符“[]”

问题描述

我正在尝试从 Firestore 获取 brews 集合中的文档。

我的代码有什么问题?

帮助我熟悉 Flutter 和 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();
  }

附上有关错误的屏幕截图

标签: firebasefluttergoogle-cloud-firestoresnapshot

解决方案


根据cloud_firestore插件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.

因此,也许对您的代码的这种修改会起作用:

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

推荐阅读