-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
  • 407
  • 1
  • 14

2 Answers2

2

Try the following:

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

 final result = list.reduce((sum, element){
 return sum + element;
 }); 
Obsidianlab
  • 407
  • 1
  • 14
1

This could do it

final sum = list.fold<int>(0, (previousValue, number) => previousValue + number);
Ivo Beckers
  • 7,280
  • 2
  • 16
  • 21