Flutter Dart fold method
Flutter Dart fold method

Hi Guy’s Welcome to Proto Coders Point. In this Flutter dart article let’s checkout How to calculate sum of array list, Find the smallest & largest number in a given list by using list fold method.

Dart fold Syntax

Future<S> fold<S>(initialValue,<function>( S previous, T element ){
// your operation here
})

In Flutter dart fold method, accept 2 parameters i.e. first-> initialValue & second -> a function that content 2 parameter (Previous & a element from the list). Here the previous value will be initialValue & will only change when programmer wants to & element will item from a list basically it keep changing in a loop.

Let’s Understand the Fold Method using below Examples

1. Calculate the Sum of List Element

In below code, The initial value will be first item from the list i.e. 3, Now in first loop value of sums = 3 and ele = 3 so 3+3=6, then in next iteration sums = 6 and ele = second item from the list i.e. 4, so 6 + 4 = 10, and then in third iteration value of sums get updated to sums = 10 and ele = next item i.e. ele = 5, so 10 + 5 = 15. like this the loop gets iterating until the end of the list item and we get addition of list as 18.

void main(){
  final numbers = [3,4,5,1,2];
 
  final sum = numbers.fold(numbers.first,(sums,ele){
    
   return sums + ele;
  });
  
  print(sum);  // 36
}

2. Find the largest number in list using fold method

In below code, To find the greatest number from a given list. Here initialValue is the first item from the list and it automatically assumed a max i.e. the largest element, and ele = 3 that keep are changing on each iteration, In the loop we check if the max < ele, if true then max is set to ele and thus we get the largest number from the given list.

void main(){
  final numbers = [3,4,5,1,2,4,2,1,4,7,0];
 
  final largest = numbers.fold(numbers.first,(max,ele){
    
   if (max < ele){
     max = ele;
   }
    
    return max;
  });
  
  print(largest);  // 7 
}

3. Find the smallest number in list using fold method

In below code, To find the lowest number from a given list. Here initialValue is the first item from the list and it automatically assumed a min i.e. the smallest element, and ele = 3 that keep are changing on each iteration, In the loop we check if the min > ele, if true then min is set to ele and thus we get the smallest number from the given list.

void main(){
  final numbers = [3,4,5,1,2,4,2,1,4,7,-1];
 
  final smallest = numbers.fold(numbers.first,(min,ele){
    
   if (min > ele){
     min= ele;
   }
    
    return min;
  });
  
  print(smallest);  // -1
}