繁体   English   中英

从 Flutter 中的 Firestore 集合中获取所有文档

[英]Get all documents from a Firestore collection in Flutter

我尝试了不同的方法,但我无法编辑代码结构

//First way
QuerySnapshot querySnapshot = await db.firestoreInstance.collection('user-history').get();
    var list = querySnapshot.docs;
    print('MY LIST ===== $list');

//Second way
    final CollectionReference collectionRef = db.firestoreInstance
        .collection(historyCollection);

    print('MY SECOND LIST ===== $list');
    collectionRef.get().then((qs) {
      qs.docs.forEach((element) {
        print('MY doc id ${element.id}');
      });
    });

在我的 firebase 集合(historyCollection)中,我有四个文档,但调试器返回空数组 []。 还有另一种方法可以通过 flutter 调用某个集合中的所有文档吗? 我正在尝试通过 FutureBuilder 组件调用此方法。

我的firestore版本是:“cloud_firestore:^0.16.0+1”

整个问题不在于这些代码片段。 这个问题是因为我的 collections 有子集合。 我读到了这个,我知道子集合可以在没有他们的祖先的情况下生存,访问父母的唯一方法是直接指定文档的确切路径和名称。 要在我的情况下使用此代码,需要添加我的整套 collections 的虚拟组件。 有关更多信息,请查看以下两个主题:

  1. -> https://firebase.google.com/docs/firestore/using-console
  2. -> Firestore DB - 以斜体显示的文档

这应该可以解决问题:

Future<List<dynamic>> getCollection(CollectionReference collection) async {
    try {
      QuerySnapshot snapshot = await collection.get();
      List<dynamic> result =  snapshot.docs.map((doc) => doc.data()).toList();
      return result;
    } catch (error) {
      print(error);
      return null;
    }
  }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM