The syntax of List.fold() method is:
T fold<T>(T initialValue, T combine(T previousValue, E element))
This fold() method of List reduces a collection to a single value by iteratively combining each element of the collection with an existing value
Parameter | Optional/Required | Description |
---|---|---|
initialValue | required | the initial value to start the accumulation |
combine | required | a function that combines the previous value and the current element to produce a new value |
List.fold() returns value of type T
.
In this example,
numbers
containing the numbers 1, 2, 3, 4, 5
.fold()
method starting with an initial value of 0
.void main() {
List<int> numbers = [1, 2, 3, 4, 5];
int sum = numbers.fold(0, (previous, current) => previous + current);
print('Sum of numbers: $sum'); // Output: Sum of numbers: 15
}
Sum of numbers: 15
In this example,
characters
containing the characters 'a', 'b', 'c', 'd', 'e'
.fold()
method starting with an initial value of an empty string ''
.void main() {
List<String> characters = ['a', 'b', 'c', 'd', 'e'];
String concatenated = characters.fold('', (previous, current) => previous + current);
print('Concatenated characters: $concatenated'); // Output: Concatenated characters: abcde
}
Concatenated characters: abcde
In this example,
fruits
containing the strings 'apple', 'banana', 'cherry'
.fold()
method starting with an initial value of 0
.void main() {
List<String> fruits = ['apple', 'banana', 'cherry'];
int totalLength = fruits.fold<int>(0, (previous, current) => previous + current.length);
print('Total length of strings: $totalLength');
}
Total length of strings: 17
In this Dart tutorial, we learned about fold() method of List: the syntax and few working examples with output and detailed explanation for each example.