【问题标题】:The operator '[]' isn't defined for the type 'Object' [duplicate]未为“对象”类型定义运算符“[]”[重复]
【发布时间】:2021-07-30 16:17:31
【问题描述】:

我正在尝试从 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();
  }

附上有关错误的屏幕截图

【问题讨论】:

标签: firebase flutter google-cloud-firestore snapshot


【解决方案1】:

根据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();
  }

【讨论】:

  • 我也试过这个方法。删除“.data”后,错误消失了。但是当我运行该项目时,它显示错误“因为 _MapStream>, List> 引发了异常”
  • @PATHimaranga 你也可以发布其余的错误吗?
【解决方案2】:

您可能正在寻找 document.data[] 而不是 document.data()[]

document.data 是一个返回 Map 的 getter,因此您只需将其查询为 document.data['someKey'] 而不是 document.data()['someKey']

所以这段代码应该可以工作:

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();
  }

【讨论】:

  • 你的意思是 |name: document.data['name'] ?? “”|。但是 ierror 显示 data 是一个对象。
  • 我已经用一些代码更新了我的答案。让我知道它是否适合您。
  • 我的错。好像 API 不久前更新了。我的代码适用于以前的版本,我还没有迁移,所以我不知道。
  • @PATHimaranga document['name'] 对你有用吗?
  • 不,因为 API 更新。更新后数据不带括号不能使用。
猜你喜欢
  • 2021-07-30
  • 2021-08-08
  • 2021-05-11
  • 2023-03-19
  • 2021-07-31
  • 1970-01-01
相关资源
最近更新 更多