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.
Table of Contents
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:
- How to Flatten a Nested List in Dart
- Dart: Converting a List to a Map and Vice Versa
- Dart: How to Add new Key/Value Pairs to a Map
- Dart: Checking whether a Map is empty
- Dart: Convert Map to Query String and vice versa
- 2 Ways to Get a Random Item from a List in Dart (and Flutter)
You can also check out our Flutter category page or Dart category page for the latest tutorials and examples.