A list literal [1, 2, 3] builds an ordered collection. add appends, and reduce folds with a closure.

Program

Play the program to append a value and sum the list.

lists.dart
Replay: real traced execution (multi-file project)
void main() {
  var nums = [1, 2, 3];
  nums.add(4);
  var total = nums.reduce((a, b) => a + b);
  print(total);
}
  1. nums ← [1, 2, 3]

    1void main() {2  var nums = [1, 2, 3];3  nums.add(4);
    values this step[1, 2, 3]nums
  2. nums ← [1, 2, 3, 4]

    2var nums = [1, 2, 3];3nums.add(4);4var total = nums.reduce((a, b) => a + b);
    values this step[1, 2, 3] [1, 2, 3, 4]nums
  3. total ← 10

    3nums.add(4);4var total = nums.reduce((a, b) => a + b);5print(total);
    values this step10total[1, 2, 3, 4]nums
  4. print(total);

    4  var total = nums.reduce((a, b) => a + b);5  print(total);6}
    output10
    values this step10total

Add, Then Reduce

  1. Start with nums: [1, 2, 3].
  2. nums.add(4) appends 4 to the end.
  3. reduce combines the list from left to right.
  4. The final total is 10. | Step | Values | | --- | --- | | start | [1, 2, 3] | | after add(4) | [1, 2, 3, 4] | | reduce total | 10 |
list literal `[1, 2, 3]` builds a `List<int>`.
add `add(x)` appends `x` in place.
reduce `reduce((a, b) => a + b)` folds the list to one value.

Exercise: lists.dart

Append one number to a list, reduce the list to a total, and print the total