Dart fold() Method

Summary: in this tutorial, you’ll learn how to use the fold() method of an Iterable object to reduce a collection to a single value.

Introduction to the Dart fold() Method #

The fold() method is a function of the Iterable object. It reduces a collection to a single value by combining each element with an existing one.

Here’s the syntax of the fold() method:

T fold<T>(
    T initialValue,
    T combine( T previousValue, E element )
)
Code language: Dart (dart)

In this syntax:

  • T is the type you want to accumulate to. It can be different from the type of the elements in the collection.
  • initialValue is the starting value for the accumulator (T).
  • combine is a function that takes the previous accumulated value (previousValue) and the current element (element), and returns a new accumulated value.

How the fold() method works:

  1. Take an initialValue of type T.
  2. Iterate over every element in the iterable Iterable<E>.
  3. For each element, call the combine() function with the current accumulated value (starting with initialValue) and the current element (element).
  4. Set the result as the new accumulated value.
  5. After the loop completes, return the final accumulated result of type T.

Calculating the Sum of Integers #

The following example shows how to use the fold() method to calculate the sum of integers:

void main() {
  List<int> numbers = [1, 2, 3];
  var result = numbers.fold(0, (total, value) => total + value);
  print(result);
}
Code language: Dart (dart)

Output:

6
Code language: Dart (dart)

How it works:

  • Step 1: 0 + 1 = 1
  • Step 2: 1 + 2 = 3
  • Step 3: 3 + 3 = 6

Calculating the Sum of Objects #

The following example uses the fold() function to calculate the total quantity of a list of items:

class Item {
  final String name;
  final int quantity;
  Item({required this.name, required this.quantity});
}

void main() {
  List<Item> items = [
     Item(name: 'apple', quantity: 1),
     Item(name: 'banana', quantity: 2),
     Item(name: 'orange', quantity: 3),
  ];

  var result = items.fold(0, (total, item) => total + item.quantity);

  print(result);
}
Code language: Dart (dart)

Output:

6
Code language: Dart (dart)

Concatenating Strings #

The following example uses the fold() method to concatenate the names of the items in the list:

class Item {
  final String name;
  final int quantity;
  Item({required this.name, required this.quantity});
}

void main() {
  List<Item> items = [
     Item(name: 'apple', quantity: 1),
     Item(name: 'banana', quantity: 2),
     Item(name: 'orange', quantity: 3),
  ];

  var result = items.fold('', (s, item) {
     if (s.isEmpty) {
        return item.name;
     }
     return s + ',' + item.name;
  });

  print(result);
}
Code language: Dart (dart)

Output:

apple,banana,orange
Code language: Dart (dart)

fold() vs. reduce() #

The following table shows the differences between the fold() and reduce() methods of an iterable object:

Featurefold()reduce()
Initial valueYou provide an initial value.Uses the first element as the initial value.
Use caseSafe to use with empty lists.Works with non-empty lists only.
Empty listReturns the initial value.Throws a StateError.
Type flexibilityThe type of the return value can differ from the elements in the list.The type of the return value must be the same as the type of elements in the list.

In general, you should use the fold() method instead of the reduce() method to reduce a collection into a single value.

Summary #

  • Use the fold() method to reduce a collection into a single value.
  • The fold() returns the initial value if the iterable is empty.
Was this tutorial helpful ?