How to add values in a Firestore cloud collection in flutter Dart?

Asked

Viewed 96 times

0

How can I add up the therebyValue' field - image below - using the Dart programming language in flutter? I tried to do as in the code below but it didn’t work.

RecuperarLista() async {
int a;
FirebaseAuth auth = FirebaseAuth.instance;
FirebaseUser usuarioLogado = await auth.currentUser();
Firestore db = Firestore.instance;
db.collection("meus Produtos").snapshots().listen(
        ( snapshot ){
      for( DocumentSnapshot item in snapshot.documents ) {
        var dados = item.data;
        int somar=0;
      somar =dados['Valor'].values.reduce((sum, element) => (sum + element));
print("somar do valor è"+ somar.toString());

      }

Cloud Firestore

1 answer

0


Declare the total variable outside of for and then add the values inside:

int total = 0;
for (DocumentSnapshot item in snapshot.documents) {
  var dados = item.data;
  total += dados['Valor'];
  print("total: " + total.toString());
}
  • It worked, thank you very much.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.