DART / CHAPTER 04

Lists, maps, and transformations

Intermediate

Control aliasing and evaluate lazy iterable results when needed.

By the end of this chapter

  • Distinguish aliases from copied lists
  • Use map keys and defaults
  • Materialize an Iterable with toList

The idea

A List is an ordered collection indexed from zero. A Map associates keys with values, and a missing-key lookup can produce null. Assignment of a collection variable copies its reference rather than duplicating the collection. If two names refer to one list, mutation through either name is visible through the other. Create a new list when independence is required.

where selects matching elements and map transforms elements, producing iterable views that commonly perform their work during iteration. Calling toList evaluates the pipeline into a stored list. This matters when the source changes after the pipeline is declared. Decide whether the result should reflect future source contents or represent a snapshot of the values now.

Dart example
void main() {
  final values = [1, 4, 6];
  final selected = values.where((x) => x > 2).map((x) => x + 1).toList();
  values.add(8);
  print(selected.join(","));
  print(values.length);
}
Result
5,7
4

toList stores the transformed values before eight is added. The original list later has four elements, while the snapshot still has two.

Try it yourself

Count labels in a Map<String, int> and use a zero fallback for missing keys.

Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.

CHECK YOUR UNDERSTANDING

Chapter checkpoint

What is printed?
final a = [2, 3];
final b = a;
b[0] = 8;
print(a[0]);