Home > Back-end >  Flutter : How to Calculate total price of a List of items in FutureBuilder
Flutter : How to Calculate total price of a List of items in FutureBuilder

Time:11-15

How to Calculate total price of a List of items in FutureBuilder ? i try this

FutureBuilder<ProModel>(
  future: futurePro,
  builder: (context, snapshot){
  if(snapshot.hasData){
    snapshot.data.pro.forEach((element) {
    subTotal = subTotal   int.parse(element.amount);
    });
  }
}

but subTotal in a continuous increasing (to infinity) when i add Text('$subTotal') snapshot.data.pro is list from json

{
"pro":[
  {"id":"1", "amount":"1784",}
  {"id":"2", "amount":"1643",}
 ]
}

CodePudding user response:

It looks like you are storing the subTotal somewhere in the surrounding widget.

As any build method, your builder callback can be called multiple times and is adding to the stored value every time it is called. So instead of

snapshot.data.pro.forEach((element) {
  subTotal = subTotal   int.parse(element.amount);
});

you can try to store the value in a local variable like this:

var subTotal = 0;
for (var p in snapshot.data.pro) {
  subTotal  = int.parse(p.amount);
}

CodePudding user response:

in your case, this line:

subTotal = subTotal   int.parse(element.amount);

exactly in this element.amount, you're trying to get the non existing amount property that doesn't exists in the elements of your list, what you have is a List<Map> and the amount key of a Map can be called only like this element[amount].

so in your case, replace with this:

 if(snapshot.hasData){
snapshot.data.pro.forEach((element) {
subTotal = subTotal   int.parse(element["amount"]);
});
 }
  • Related