# Flutter & Dart: reduce() examples

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``

## 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.

Subscribe
Notify of
Inline Feedbacks

Related Articles

September 17, 2023

September 17, 2023

September 16, 2023

September 15, 2023

September 15, 2023

September 15, 2023

September 15, 2023

September 14, 2023

September 13, 2023

September 13, 2023

September 11, 2023

September 11, 2023

September 10, 2023

September 1, 2023

August 24, 2023

August 24, 2023

August 19, 2023