迭代 Firestore 集合上的文档求和值的最佳方法是什么?

Dan*_*lho 3 firebase flutter google-cloud-firestore

我试图找出如何使用 Flutter 中的“cloud_firestore”包对 Firestore 集合中每个文档中存储的值进行求和。

我尝试了这段代码:

double queryValues() {
    total = 0.0;

    Firestore.instance
        .collection('myCollection')
        .snapshots()
        .listen((snapshot) {
        snapshot.documents.forEach((doc) => this.total += 
                                            doc.data['amount']);
    });
    debugPrint(this.total.toString());
    return total;
  }
Run Code Online (Sandbox Code Playgroud)

但我最终打印了 0.0 结果。如果我删除第一行(总计= 0.0。),我会得到总和,但如果我重新加载,值就会加倍(加起来等于旧的总计)。

我知道他们说最好的解决方案是在每次写入文档时使用云函数存储这个聚合值,但这会很痛苦,因为我想按某些范围周期提供总计以供用户查询(月、年、周) )。这些查询会产生少量文档,因此对我来说,迭代结果集合是理想的选择)。

这是我发布的第一个问题,我非常感谢对此的任何想法。

Avn*_*mar 5

 CollectionReference _documentRef=Firestore.instance.collection("User");

   _documentRef.getDocuments().then((ds){
     if(ds!=null){
            ds.documents.forEach((value){
              print(value.data);
            });
     }
   });
Run Code Online (Sandbox Code Playgroud)