Iterable.fold(initial, combine) collapses a list into a single value by carrying an accumulator across the elements. combine is called once per element with (accumulator, element) and returns the next accumulator. The initial value sets the type and starting state of the accumulator. The original list is never modified, and fold finishes with the final accumulator regardless of how many elements were folded.

Program

Play the program to fold [3, 5, 2] into a running sum with (sum, n) => sum + n, then print the result.

fold_reduce.dart
Replay: real traced execution (multi-file project)
void main() {
  var amounts = [3, 5, 2];
  var total = amounts.fold(0, (sum, n) => sum + n);
  var label = 'total=$total';
  print(label);
}
  1. amounts ← [3, 5, 2]

    1void main() {2  var amounts = [3, 5, 2];3  var total = amounts.fold(0, (sum, n) => sum + n);
    values this step[3, 5, 2]amounts
  2. step ← 0 + 3 = 3

    2var amounts = [3, 5, 2];3var total = amounts.fold(0, (sum, n) => sum + n);4var label = 'total=$total';
    values this step0 + 3 = 3step
  3. step ← 3 + 5 = 8

    2var amounts = [3, 5, 2];3var total = amounts.fold(0, (sum, n) => sum + n);4var label = 'total=$total';
    values this step3 + 5 = 8step
  4. step ← 8 + 2 = 10

    2var amounts = [3, 5, 2];3var total = amounts.fold(0, (sum, n) => sum + n);4var label = 'total=$total';
    values this step8 + 2 = 10step
  5. total ← 10

    2var amounts = [3, 5, 2];3var total = amounts.fold(0, (sum, n) => sum + n);4var label = 'total=$total';
    values this step10total[3, 5, 2]amounts
  6. label ← total=10

    3var total = amounts.fold(0, (sum, n) => sum + n);4var label = 'total=$total';5print(label);
    values this steptotal=10label10total
  7. print(label);

    4  var label = 'total=$total';5  print(label);6}
    outputtotal=10
    values this steptotal=10label
fold `list.fold(init, combine)` walks the elements left to right, calling `combine(accumulator, element)` and feeding the result back in as the next `accumulator`.
initial value The initial accumulator sets the type and the starting state. Here `0` keeps the accumulator an `int`; folding into a `String` would start with `''`.
step progression The trace re-visits the fold line three times to show each `combine` call: `0 + 3 = 3`, `3 + 5 = 8`, `8 + 2 = 10`. The fourth visit binds the final value to `total`.