-1

I have an array in the flutter

 final list = [1, 2, 3, 4, 5];

I want to loop through the array to calculate the sum of all the items in the array,how i can?

Obsidianlab
  • 667
  • 1
  • 4
  • 24

2 Answers2

2

Try the following:

 final list = [1, 2, 3, 4, 5];

 final result = list.reduce((sum, element){
 return sum + element;
 }); 
Obsidianlab
  • 667
  • 1
  • 4
  • 24
1

This could do it

final sum = list.fold<int>(0, (previousValue, number) => previousValue + number);
Ivo
  • 18,659
  • 2
  • 23
  • 35