【问题标题】:Get all documents from a Firestore collection in Flutter从 Flutter 中的 Firestore 集合中获取所有文档
【发布时间】:2021-07-29 18:36:10
【问题描述】:

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

//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)中,我有四个文档,但调试器返回空数组 []。还有另一种方法可以通过颤振调用某个集合中的所有文档吗? 我正在尝试通过 FutureBuilder 组件调用此方法。

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

【问题讨论】:

  • 当我们使用await时不必使用then,所以第一种方式去掉then,QuerySnapshot querySnapshot = await db.firestoreInstance.collection(historyCollection).get();并确保写出正确的集合名称
  • @Anna 我编辑了我的帖子并尝试这样做告诉我,但仍然没有。
  • 你在这个 print('MY LIST ===== $list'); 中得到了什么??
  • 尝试打印列表的长度
  • I/flutter ( 7767): MY LIST ===== [] I/flutter ( 7767): MY LIST LENGTH ===== 0 I/flutter ( 7767): MY SECOND LIST ===== [] I/flutter ( 7767): MY SECOND LIST LENGTH ===== 0

标签: flutter dart google-cloud-firestore


【解决方案1】:

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

  1. ->https://firebase.google.com/docs/firestore/using-console
  2. ->Firestore DB - documents shown in italics

【讨论】:

    【解决方案2】:

    这应该可以解决问题:

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

    【讨论】:

    • 对我不起作用,它只是具有相同代码的方法。
    • 抱歉,代码有错误。再试一次,它现在应该可以工作了。您只需将引用传递给要从中检索文档的集合。
    • 第一种代码是正确的“recipes.docs..”。问题是每次我得到空数组[]。我不知道是什么问题。我一遍又一遍地重新考虑这段代码,但我没有发现错误。
    • 这很奇怪,你引用的是正确的集合吗?另外,你能分享你的firestore规则吗?这可能是问题的根源。
    • rules_version = '2'; service cloud.firestore { match /databases/{database}/documents { match /{document=**} { allow read, write: if true; } } } 仅供测试,所以我允许大家读写
    猜你喜欢
    • 1970-01-01
    • 2020-08-08
    • 2021-12-16
    • 2019-02-05
    • 1970-01-01
    • 2019-08-05
    • 1970-01-01
    • 1970-01-01
    • 2018-03-18
    相关资源
    最近更新 更多