【问题标题】:Query specific field in Firestore snapshot查询 Firestore 快照中的特定字段
【发布时间】:2020-06-12 02:34:24
【问题描述】:

我创建了这个获取特定文档快照的流。在文档中有一个名为 tripAttractions 的数组,我想将它构建到一个列表中。问题是,我如何从快照中访问这个特定的数组?

Stream<QuerySnapshot> getAttractions(BuildContext context) async* {
   Firestore.instance
      .collection('trips')
      .document(documentId)
      .snapshots(includeMetadataChanges: true);

}

该列表显示了我如何尝试访问快照 tripAttractions 数据,但这不起作用。

ListView.builder(
   itemCount: snapshot.data['tripAttractions'].length,
                    itemBuilder: (BuildContext context, int index) =>
                        tripAttractionsCards(
                            context, index, snapshot.data['tripAttractions']),
                  );

firestore 文档中的数组

【问题讨论】:

    标签: firebase flutter google-cloud-firestore


    【解决方案1】:

    很可能您只是缺少项目构建器中的数组访问器:

    ListView.builder(
       itemCount: snapshot.data['tripAttractions'].length,
            itemBuilder: (BuildContext context, int index) =>
                tripAttractionsCards(
                    context, index, snapshot.data['tripAttractions'][index]),
          );
    

    【讨论】:

    • 嘿弗兰克!我尝试这样做,但出现以下错误:NoSuchMethodError:方法 '[]' 在 null 上被调用。接收者:null,尝试调用:[]("tripAttractions")
    • 有趣:您可能想检查一下 snapshot.data 正在为您做什么,因为您似乎正在尝试从空的或不存在的快照中获取数据。
    • 我刚刚创建了一个 if 语句来检查并且快照查询没有返回任何数据
    • 谢谢我发现了这个问题!我会发布我做错了什么
    • 再次感谢弗兰克!你第二次用我的项目救了我。
    【解决方案2】:

    好的,问题是错误地调用了 QuerySnapshot。我应该使用 DocumentSnapshot 因为我直接调用一个文档。我还必须添加 yield* 以从 firestore 返回数据。

    Stream<DocumentSnapshot> getAttractions(BuildContext context) async* {
       yield* Firestore.instance
          .collection('trips')
          .document(documentId)
          .snapshots(includeMetadataChanges: true);
    }
    

    我可以通过在 streamBuilder 中添加 if 语句来检查快照是否正在发送任何数据来解决此问题。

       if (!snapshot.hasData) return Text("Loading");
    

    【讨论】:

      猜你喜欢
      • 2021-06-17
      • 1970-01-01
      • 1970-01-01
      • 2018-11-14
      • 2021-05-02
      • 2019-09-03
      • 1970-01-01
      • 2022-01-24
      • 1970-01-01
      相关资源
      最近更新 更多