Dart Runes fold()
Syntax & Examples

Runes.fold() method

The `fold` method in Dart reduces a collection to a single value by iteratively combining each element of the collection with an existing value.


Syntax of Runes.fold()

The syntax of Runes.fold() method is:

 T fold<T>(T initialValue, T combine(T previousValue, int element)) 

This fold() method of Runes 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 takes the previous accumulated value and the current element, and returns the new accumulated value.

Return Type

Runes.fold() returns value of type T.



✐ Examples

1 Folding a list of numbers to calculate the sum

In this example,

  1. We create a list numbers containing integers.
  2. We use the fold() method with an initial value of 0 and a function that adds the previous value to the current element.
  3. We print the final accumulated sum to standard output.

Dart Program

void main() {
  List<int> numbers = [1, 2, 3];
  int sum = numbers.fold(0, (previousValue, element) => previousValue + element);
  print(sum);
}

Output

6

2 Folding a list of strings to concatenate them

In this example,

  1. We create a list words containing strings.
  2. We use the fold() method with an initial value of an empty string and a function that concatenates each word with a space.
  3. We print the final combined string after trimming any leading or trailing spaces.

Dart Program

void main() {
  List<String> words = ['hello', 'world'];
  String combined = words.fold('', (previousValue, word) => previousValue + word + ' ');
  print(combined.trim());
}

Output

hello world

3 Folding a set of numbers to calculate the product

In this example,

  1. We create a set uniqueNumbers containing integers.
  2. We use the fold() method with an initial value of 1 and a function that multiplies the previous value with the current number.
  3. We print the final accumulated product to standard output.

Dart Program

void main() {
  Set<int> uniqueNumbers = {1, 2, 3};
  int product = uniqueNumbers.fold(1, (previousValue, number) => previousValue * number);
  print(product);
}

Output

6

Summary

In this Dart tutorial, we learned about fold() method of Runes: the syntax and few working examples with output and detailed explanation for each example.