๐ŸŽ“ A1Learner
๐Ÿ”
0 of 37 lessons completed

Dart Collection Transformations

A transformation builds a new collection from the values of an existing one. The original collection keeps its values and its order.

Doubling every value with map

The map method multiplies each number by two. The toList call turns the lazy result into a list that print can show.

void main() {
  var numbers = [1, 2, 3];
  var doubled = numbers.map((n) => n * 2).toList();
  print(doubled);
}

Map stays lazy until read

Without toList, the map result is an iterable, not a list. Print shows it in parentheses instead of brackets.

void main() {
  var numbers = [1, 2, 3];
  var doubled = numbers.map((n) => n * 2);
  print(doubled);
}

Keeping values with where

The where method tests each number. Only the numbers greater than two survive the test.

void main() {
  var numbers = [1, 2, 3, 4];
  var big = numbers.where((n) => n > 2).toList();
  print(big);
}

Flattening pairs with expand

Each inner list holds a pair of numbers. The expand method replaces each pair with its two numbers, one after the other.

void main() {
  var pairs = [
    [1, 2],
    [3, 4]
  ];
  var flat = pairs.expand((pair) => pair).toList();
  print(flat);
}

Chaining where and map

The where call filters first and the map call transforms what remains. The chain reads left to right.

void main() {
  var numbers = [1, 2, 3, 4];
  var result = numbers.where((n) => n > 1).map((n) => n * 10).toList();
  print(result);
}

Example

void main() {
  var prices = [5, 12, 8, 20];
  var deals = prices.where((p) => p < 10).map((p) => p + 1).toList();
  print(deals);
  print(prices);
}

Key points

  • The map method applies a function to every value and returns the results.
  • The result of map is lazy, so nothing is computed until the values are read.
  • Calling toList on the result builds a real list from it.
  • The where method keeps only the values that pass a test.
  • The expand method turns each value into several values and flattens them into one sequence.
  • Transformations can chain, so the output of one method feeds the next.

In this example, where keeps the prices below ten, which are 5 and 8. The map call adds one to each kept price. The last print shows the original list with all four prices unchanged.

Note

a transformation never changes the list it starts from.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท DartPad

Exercise

What does numbers.map((n) => n + 1).toList() give for the list [1, 2, 3]?