Flutter & Dart: reduce() examples

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

A few examples of how to use the reduce() method in Dart.

1. Find the highest number (max) in a list

void main() {
  final myList = [1, 3, 5, 4, 9, 11, 0, -4, -10];
  final result = myList.reduce((max, element){
    if(max > element){
      return max;
    } else {
      return element;
    }
  }); 
  print(result);
}

Output:

11

2. Find the smallest number (min) in a list

void main() {
  final myList = [1, 3, 5, 4, 9, 11, 0, -4, -10];
  final result = myList.reduce((min, element){
    if(min < element){
      return min;
    } else {
      return element;
    }
  }); 
  print(result);
}

Output:

-10

3. Calculate the sum of a list

void main() {
  final myList = [1, 3, 5, 4, 9, 11, 0, -4, -10];
  final result = myList.reduce((sum, element){
    return sum + element;
  }); 
  print(result);
}

Output:

19

Related Articles

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