Flutter & Dart: fold() method examples

Last updated on October 12, 2020 The Frog Loading... Post a comment

Some common use cases of the fold() method in Dart.

Calculating the sum of a list

void main() {
  final myList = [1, 3, 5, 8, 7, 2, 11];
  final result = myList.fold(0, (sum, element) => sum + element);
  
  print(result);
}

Output:

37

Finding the biggest number in a list

void main() {
  final myList = [1, 3, 5, 8, 7, 2, 11];
  final result = myList.fold(myList.first, (max, element){
    if(max < element) max = element; 
    return max; 
  });
  
  print(result);
}

Output:

11

Find the smallest number in a list

void main() {
  final myList = [10, 3, 5, 8, 7, 2, 11];
  final result = myList.fold(myList.first, (min, element){
    if(min > element) min = element; 
    return min; 
  });
  
  print(result);
}

Output:

2

Related Articles

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x