如何从Firebase文档快照获取子集合 [英] how to get subcollection from a firebase document snapshot

查看:41
本文介绍了如何从Firebase文档快照获取子集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的firestore数据库的结构如下:

I structured my firestore database as follow:

为了显示数据波动,我使用streambuilder,如下所示:

to display the data in flutter i use streambuilder as follow:

StreamBuilder<QuerySnapshot>(
      stream: Firestore.instance.collection('myCollection').snapshots(),
      builder: (context, snapshot) {
        return Container(
          child: ListView.builder(    
            itemCount: snapshot.data.documents.length,
            itemBuilder: (BuildContext context, int index) =>
                _buildListItem(context, snapshot.data.documents[index]),
          ),
        );
      }),
Widget _buildListItem(BuildContext context, DocumentSnapshot document) { 

 return ListTile(
title: Row(
  children: <Widget>[
    Text(document.documentID),
    Spacer(),
    Text(document['allocatedSource'].toString()),
  ],
),

我如何像这样访问子集合:字幕:文本(document.documentID.collection('post').document).

how do I access the subcollection like this: subtitle: Text(document.documentID.collection('post').document).

如果我声明流如下,我可以访问它:

I can access that if i declare the stream as follow:

StreamBuilder<QuerySnapshot>(
      stream: Firestore.instance
          .collection('myCollection')
          .document(documentId)
          .collection('post')
          .snapshots(),...

,但随后我将失去对集合中documentID的访问权限.我应该声明2个流还是将streambuilder嵌套?

but then I will lose the access to the documentID from the collection. Should I declare 2 stream or nest the streambuilder?

推荐答案

子集合数据不包括在文档快照中.Firestore查询很浅,只考虑单个集合中的文档.

Subcollection data are not included in document snapshots. Firestore queries are shallow, and only consider documents within a single collection.

如果需要子集合数据,则必须使用事先知道的子集合名称进行新查询.

If you want subcollection data, you'll have to make new query using the subcollection name that you know ahead of time, as you have seen.

而且,我要指出的是,您没有在第二个查询中失去"对 documentId 的访问权.它仍在内存中,您可以随意使用它.您还可以浏览父文档和集合以获取所需的ID.

And, I will point out that you haven't "lost" access to documentId in the second query. It's still in memory, and you can use it at will. You can also walk up the parent document and collections to get the ID you're looking for.

这篇关于如何从Firebase文档快照获取子集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆