【问题标题】:Why does Firebase colletion().getDocuments() return null or []? [closed]为什么 Firebase colletion().getDocuments() 返回 null 或 []? [关闭]
【发布时间】:2020-11-01 00:08:43
【问题描述】:

我有一个名为 market 的集合,它有两个我可以在 firebase 中确认的文件。

我现在正在尝试获取该集合中的文档数量,如下所示:-

getAllItemsForSell()async {
    final snapshot = await Firestore.instance.collection('market').getDocuments();
    final documents = snapshot?.documents;

    print(documents); // []

  }

上面的函数打印出'[]',我做错了什么? 我在互联网上到处寻找,但似乎没有任何帮助。

请帮忙?我是 Flutter Firebase 世界的新手,在此先感谢。

【问题讨论】:

  • 你为什么期待不同的东西?空数组对于空集合来说是完全有意义的,但我们看不出是否是这种情况。请编辑问题以解释您的期望,可能会显示您打算接收的文件的屏幕截图。

标签: firebase flutter dart google-cloud-firestore


【解决方案1】:

要查看该特定集合中的文档数量,请尝试从 users 集合中获取 documentId 并通过像这样将其传递给市场集合来遍历它

 int sampleNum =0;
getAllItemsForSell()async {
        QuerySnapshot users =  await Firestore.instance.collection('market').getDocuments();
        for(DocumentSnapshot docs in users.documents){
          QuerySnapshot doc = await Firestore.instance.collection('market').document(docs.documentID).collection('marketPosts').getDocuments();
          sampleNum = doc.documents.length;
          //posts = doc.documents.map((doc) => Post.fromDocument(doc)).toList();
        }
        print(sampleNum.toString() +' **********');
      }

【讨论】:

    【解决方案2】:

    查询按预期工作。您的“市场”集合中实际上没有任何文档 - 它完全是空的。当您在控制台中看到斜体的文档 ID 时,这意味着没有文档,但该文档下嵌套了子集合。 ID 位于控制台中,因此您可以点击进入它们。

    另见:

    【讨论】:

      【解决方案3】:

      为什么你不在函数前使用Future<void> 或任何类型。如果它不起作用,请阅读FlutterFire 的文档,这是链接https://firebase.flutter.dev/docs/firestore/usage#document--query-snapshots 而且我认为只需将getDocuments() 更改为get() 就可以了,

      Future<void> getAllItemsForSell()async {
          final snapshot = await 
          Firestore.instance.collection('market').getDocuments();
          final documents = snapshot?.documents;
      
          print(documents); // []
      
        }
      

      【讨论】:

      • 我仍然遇到同样的问题,并且使用 'get()' 会引发错误“没有为类型 'CollectionReference' 定义方法 'get'。”
      猜你喜欢
      • 2019-11-22
      • 2020-04-30
      • 2013-06-11
      • 2019-05-21
      • 1970-01-01
      • 2021-09-27
      • 1970-01-01
      • 2019-10-28
      • 1970-01-01
      相关资源
      最近更新 更多