【问题标题】:Flutter Firestore - The method 'documents' isn't defined for the type 'Stream'Flutter Firestore - 没有为“Stream”类型定义方法“documents”
【发布时间】:2020-10-01 06:54:09
【问题描述】:

我正在尝试遍历文档中的集合(使用 for 循环)并从每个集合文档中获取和捕获数据。当我第一次尝试这个时,我使用了一个流来监听数据,但是由于异步函数,该函数总是会返回一个空数组。

我的代码

for (final day in daysRunOn) {
  databaseReference
      .collection('users')
      .document(user.uid)
      .collection(day)
      .snapshots()
      .documents((snapshot) {

      });

}

This post 建议我不应该使用流,所以我删除了它。我现在正在尝试运行它,但我在 .documents 部分不断收到错误消息,上面写着“没有为类型 'Stream' 定义方法 'documents'。”但我不明白这仍然是一个流的方式或原因。

堆栈溢出的建议方法

double queryValues() async {
  total = 0.0;

  docs = await Firestore.instance
      .collection('myCollection')
      .snapshots()
      .documents((snapshot);
   docs.forEach((doc) => this.total += doc.data['amount']));
   debugPrint(this.total.toString());
   return total;
  }

任何帮助将不胜感激!

【问题讨论】:

    标签: flutter asynchronous google-cloud-firestore


    【解决方案1】:

    试试这样的:

    getDocs() async { 
      total = 0.0;
    
      snapshot = await Firestore.instance
          .collection('myCollection')
          .snapshots();
    
      docs = snapshot.data.documents;
      docs.forEach((doc) => this.total += doc.data['amount']));
      debugPrint(this.total.toString());
      return total;
    }
    

    【讨论】:

      【解决方案2】:

      试试这个代码

          List<String> daysRunOn = ['day1','day2','...'];
          int x = 0;
          double total = 0.0;
      
          Future<double> getTotal() async {
           if(x == 0) total = 0.0;
           var querySnapshot = await 
             Firestore.instance.collection('users/${user.uid}/${daysRunOn[x]}').getDocuments();
           querySnapshot.documents.forEach((doc) => total += doc.data['amount']);
           if(x == daysRunOn.length-1){
             //  the loop has finished
             x = 0;
             debugPrint(total.toString());
             return total;
           } else {
             x++;
             return getTotal();
           }
         }
      

      【讨论】:

        猜你喜欢
        • 2021-02-09
        • 2021-08-21
        • 2021-05-18
        • 2021-10-04
        • 2020-11-23
        • 2021-11-19
        • 1970-01-01
        • 2019-08-14
        • 2020-10-23
        相关资源
        最近更新 更多