Kinda Code
Home/Dart/Flutter & Dart: reduce() examples

Flutter & Dart: reduce() examples

Last updated: February 06, 2023

In Dart, the reduce() method (of the Iterable class), as its name describes itself, executes a “reducer” callback function (provided by you) on each element of the collection, in order, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the collection is a single value.

Below are a few examples of using the reduce() method in Dart.

Finding the Max value

This program finds the highest number from a given list of numbers:

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

Finding the Min value

This code finds the smallest number in a given 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

Calculating Sum

The code below calculates the total amount resulting from the addition of element numbers 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

You can find more information about the reduce() method in the Dart official docs.

Wrapping Up

We’ve walked through more than one example of making use of the reduce() method in Dart. They’ve clearly demonstrated some real-world use cases of data aggregation. Continue learning more useful and exciting stuff in Dart and Flutter by taking a look at the following articles:

You can also check out our Flutter category page or Dart category page for the latest tutorials and examples.

Related Articles