遍历Firestore集合中的总和值的文档的最佳方法是什么? [英] What's the best way to iterate through documents on a Firestore collection summing values?

查看:58
本文介绍了遍历Firestore集合中的总和值的文档的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Flutter的"cloud_firestore"包,找出如何对存储在Firestore集合中每个文档上的值求和.

I'm trying to find out how to sum a value stored on every document inside a Firestore colletion, using the "cloud_firestore" package from Flutter.

我尝试了以下代码:

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

但是我最终将结果打印为0.0.如果删除第一行(总计= 0.0.),则总和有效,但如果重新加载,则值将增加一倍(总计为原来的总数).

But I end up printing 0.0 as result. If I remove the first line (total = 0.0.) I get the sum to work, but if I reload the values are doubling (adding up to the old total).

我知道他们说最好的解决方案是在每次写入文档时都使用Cloud Function存储此汇总值,但是这很麻烦,因为我想在某些范围内提供总计值供用户查询(月,年,周).这些查询产生的文档数量很少,所以对我来说,仅迭代结果集合是理想的选择.

I known they say the best solution is to store this aggregated value using a Cloud Function on every document write, but that would be a pain as I want to make totals by some range periods available for the user to query (month, year, week). Those queries result on a small number of documents, so for me it would be ideal just to iterate over the resulting collection).

这是我发布的第一个问题,对此我深表感谢.

This is my first question posted and I really appreciate any thoughts on this.

推荐答案

如果您使用的是异步函数,则可以在listen()方法内完成所有工作,或者在方法外等待直到确定内部所有操作都已完成.

If you are using an async function either you do all your work inside the listen() method or wait outside it til you are sure everything has finished inside.

处理第二种情况的颤振"方式是使用setState(). build()具有初始外部值的窗口小部件树,并且当异步函数完成时,调用setState(),以便使用新值重建窗口小部件树.

The "Flutter" way of handling the second case is using setState(). You build() the widget tree with the initial outside value and when the async function finishes you call setState() so the widget tree is rebuilt with the new value.

(作为一个补充说明,在异步功能内,您可以使用在上一个操作上累积的fold()列表方法).

(As a side note, inside the async function you could use the fold() list method that accumulates on the previous operation).

这是一个完整的简单应用,将使用外部总价值:

Here is a complete simple app that would use the external total value:

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  double total = 0.0;

  @override
  initState() {
    super.initState();
    queryValues();
  }

  void queryValues() {
    Firestore.instance
        .collection('myCollection')
        .snapshots()
        .listen((snapshot) {
      double tempTotal = snapshot.documents.fold(0, (tot, doc) => tot + doc.data['amount']);
      setState(() {total = tempTotal;});
      debugPrint(total.toString());
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(child: Text("Total: $total")),
    );
  }
}

这篇关于遍历Firestore集合中的总和值的文档的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆