title: What's the best way to iterate through documents on a Firestore collection summing values?
body: <p>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. </p>
  
  <p>I tried this code: </p>
  
  <pre><code>double queryValues() {
      total = 0.0;
  
      Firestore.instance
          .collection('myCollection')
          .snapshots()
          .listen((snapshot) {
          snapshot.documents.forEach((doc) =&gt; this.total += 
                                              doc.data['amount']);
      });
      debugPrint(this.total.toString());
      return total;
    }
  </code></pre>
  
  <p>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).</p>
  
  <p>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).</p>
  
  <p>This is my first question posted and I really appreciate any thoughts on this.</p>