how to sum values of a field inside a firestore collection related to another collection in flutter 2.0

Issue

I’m a little lost here, I’m trying to get the sum of a specific field, my code here:

Future _sumCarta() async {
    await _firebaseServices.usersRef
        .doc(currentUser)
        .collection('Cart')
        .get()
        .then((querySnapshot) {
      querySnapshot.docs.forEach((element) async {
        // here I want to sum
         num value =  element.data()["price"];
      });
    });
  }

I want to get the sum result of all documents, any help or ideas are welcome, thank you

Solution

Wouldn’t that be:

num sum = 0.0;
querySnapshot.docs.forEach((element) async {
  num value = element.data()["price"];
  sum = sum + value;
});
print(sum)

Answered By – Frank van Puffelen

Answer Checked By – Katrina (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.