Dart Tutorials

Dart List fold()
Syntax & Examples

Syntax of List.fold()

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

Parameters

ParameterOptional/RequiredDescription
initialValuerequiredthe initial value to start the accumulation
combinerequireda function that combines the previous value and the current element to produce a new value

Return Type

List.fold() returns value of type T.



✐ Examples

1 Sum of numbers

In this example,

  1. We create a list named numbers containing the numbers 1, 2, 3, 4, 5.
  2. We then use the fold() method starting with an initial value of 0.
  3. The provided function accumulates the sum of all elements.
  4. The final sum is printed to standard output.

Dart Program

void main() {
  List&lt;int&gt; 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
}

Output

Sum of numbers: 15

2 Concatenated characters

In this example,

  1. We create a list named characters containing the characters 'a', 'b', 'c', 'd', 'e'.
  2. We then use the fold() method starting with an initial value of an empty string ''.
  3. The provided function concatenates all characters into a single string.
  4. The concatenated string is printed to standard output.

Dart Program

void main() {
  List&lt;String&gt; characters = ['a', 'b', 'c', 'd', 'e'];
  String concatenated = characters.fold('', (previous, current) => previous + current);
  print('Concatenated characters: $concatenated'); // Output: Concatenated characters: abcde
}

Output

Concatenated characters: abcde

3 Total length of strings

In this example,

  1. We create a list named fruits containing the strings 'apple', 'banana', 'cherry'.
  2. We then use the fold() method starting with an initial value of 0.
  3. The provided function accumulates the total length of all strings.
  4. The total length is printed to standard output.

Dart Program

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');
}

Output

Total length of strings: 17

Summary

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.