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

1.1k Views Asked by At

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

1

There are 1 best solutions below

1
On BEST ANSWER

Wouldn't that be:

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