Weiß Schneider
Weiß Schneider

Reputation: 185

how to addition doubles in flutter

i have a list of doubles, that i want to show the result of addition all of those, i did this before but i couldn't show those with this , indeed, i got the same element in each time what is the best way to do that, i'm really confused

void main() {
  List<double> list= [1.0,1.0,1.0,1.0,0.8,52.9];
  double total = 0.0;
  for (var item in list) {
  
    var all= item+ total;
    print(all);
  }
}

please tell me what i did wrong

Upvotes: 0

Views: 1938

Answers (3)

HBS
HBS

Reputation: 670

You can use the fold method as well:

void main() {
  final list = [1.0,1.0,1.0,1.0,0.8,52.9];
  final result = list.fold(0, (a, b) => a + b);
  print(result);
}

Upvotes: 0

Timoteo Holanda
Timoteo Holanda

Reputation: 46

Adding to João's answer:

The best looking answer could be something like:

var result = list.reduce((a,b) => a+b));

The reduce method of a list have the same effect on a list.

Upvotes: 3

J. S.
J. S.

Reputation: 9625

You have an all variable being declared inside the for loop. It gets re-declared every time the loop runs. If you just want the total value, you just add it on every loop and print it out:

void main() {
  List<double> list= [1.0,1.0,1.0,1.0,0.8,52.9];
  double total = 0.0;
  for (var item in list) {
    total = item + total;
    print(total);
  }
}

Upvotes: 0

Related Questions