Skip to content
LumenaryAcademy
Practice 55 min

Collections and generics

Lists, sets and maps; collection literals with if, for, spreads and null-aware elements; lazy iterables; and generic code.

Code tested · 5AI-draftedAwaiting review by a computer scientist
MotivationH

Data in bulk

Almost every program handles collections: the messages in a chat, the products in a basket, the words in a document. Dart has three general-purpose collection types built in, List, Set and Map, plus the Iterable interface that lets you process any of them with a vocabulary of methods such as map, where and fold.

What sets Dart apart is how collections are built. Flutter code constructs lists of widgets constantly, often depending on state ("show this button only if the user is logged in"), and Dart's collection literals let you write that inline with if, for and spreads instead of a sequence of add calls. This lesson covers the three types, those literals, the laziness of iterables, and the generics that make all of it type-safe.

Worked examplesH

Lists, sets and maps

TypeLiteralOrderedUniqueLook up by
List[1, 2, 3]yesnoindex, from 0
Set{1, 2, 3}insertion order (default)yesmembership
Map{'a': 1}insertion order (default)keys arekey
dart
void main() {
  // Lists: ordered, indexed from 0, growable.
  final queue = ['Ama', 'Bilal', 'Chen'];
  queue.add('Dara');
  queue.insert(0, 'Zoe');
  queue.remove('Bilal');
  print('$queue ${queue.length} ${queue[1]} ${queue.last}');
  print(queue.indexOf('Chen'));
  print(queue.sublist(1, 3));

  final scores = [72, 95, 58, 88];
  scores.sort(); // sorts in place
  print(scores);
  scores.sort((a, b) => b.compareTo(a)); // a comparator: descending
  print(scores);

  // Sets: unordered collections of unique values (but iteration keeps insertion order).
  final morning = {'Ana', 'Kofi', 'Mei', 'Ravi'};
  final evening = {'Mei', 'Omar', 'Ravi'};
  print(morning.intersection(evening));
  print(morning.union(evening).length);
  print(morning.difference(evening));
  print(morning.add('Ana')); // false: already there

  // Maps: keys to values. Looking up a key gives a nullable value.
  final stock = {'apples': 12, 'mangoes': 5};
  stock['pears'] = 7;
  stock.update('apples', (n) => n + 3);
  stock.update('kiwis', (n) => n + 1, ifAbsent: () => 1);
  print(stock);
  print('${stock['mangoes']} ${stock['figs']} ${stock['figs'] ?? 0}');
  print(stock.containsKey('pears'));
  for (final MapEntry(:key, :value) in stock.entries) {
    if (value > 6) print('$key: $value');
  }
}
text
[Zoe, Ama, Chen, Dara] 4 Ama Dara
2
[Ama, Chen]
[58, 72, 88, 95]
[95, 88, 72, 58]
{Mei, Ravi}
5
{Ana, Kofi}
false
{apples: 15, mangoes: 5, pears: 7, kiwis: 1}
5 null 0
true
apples: 15
pears: 7
  • Lists grow and shrink with add, insert, remove and removeAt. Indexing out of range throws a RangeError. sort sorts in place; give it a comparator to choose the order, typically built from compareTo. sublist(1, 3) takes positions 1 and 2.
  • Sets keep one copy of each value; add returns false when the value was already there. The default Set (a LinkedHashSet) iterates in insertion order, so printing is predictable. intersection, union and difference do what their names say.
  • Maps. Reading stock['figs'] gives null for a missing key, so the type of a lookup is nullable (int?) and the compiler makes you handle the absent case, typically with ??. update changes a value with a function, with ifAbsent for missing keys. Like sets, default maps remember insertion order.
  • The loop for (final MapEntry(:key, :value) in stock.entries) takes each entry apart with a pattern; the syntax :key means "the key property, bound to a variable named key". Patterns get a lesson of their own soon.
IntuitionH

Collections are shared objects

In Dart, a list, set or map is an object, and a variable holds a reference to it. Assigning the variable, or passing it to a function, shares the same collection:

dart
final a = [1, 2];
final b = a;        // b refers to the same list
b.add(3);
final c = [...a];   // a new list with the same elements
c.add(4);
print('$a $b $c');  // [1, 2, 3] [1, 2, 3] [1, 2, 3, 4]

final grid = [[0, 0], [0, 0]];
final copy = [...grid];
copy[0][0] = 9;
print(grid);        // [[9, 0], [0, 0]]

b.add(3) changed "both" lists because there is only one. A spread (or List.of(a), or a.toList()) makes a new list, but it is a shallow copy: the outer list is new, while the inner lists are still shared, so changing copy[0][0] changed grid too. If you come from Swift, where arrays are values, this is the biggest difference to keep in mind; if you come from Python, Java or JavaScript, it is what you expect. Defensive copies and unmodifiable views, shown below, are how Dart code protects collections it owns.

Worked examplesH

Building collections with literals

dart
String? specialFor(String day) => day == 'Sat' ? 'pancakes' : null;

void main() {
  const base = ['bread', 'milk'];
  const isWeekend = true;
  final special = specialFor('Sat');
  final forgotten = specialFor('Tue');
  final extras = <String>[];

  // Collection if, collection for, spreads and null-aware elements build lists declaratively.
  final shopping = [
    ...base,
    if (isWeekend) 'coffee',
    for (final day in ['Mon', 'Thu']) 'fruit for $day',
    ?special, // null-aware element (Dart 3.8): added only if not null
    ?forgotten,
    ...extras,
  ];
  print(shopping);

  // The same ideas work for maps and sets.
  final prices = {'bread': 2, 'milk': 1, 'coffee': 6};
  final expensive = {
    for (final MapEntry(:key, :value) in prices.entries)
      if (value > 1) key: value,
  };
  print(expensive);

  // Beware: {} on its own is an empty Map, not a Set.
  final what = {};
  final set = <String>{};
  print('${what.runtimeType} ${set.runtimeType}');

  // Lists compare by identity, not contents.
  print([1, 2] == [1, 2]);
  print(const [1, 2] == const [1, 2]); // identical constants are one object
}
text
[bread, milk, coffee, fruit for Mon, fruit for Thu, pancakes]
{bread: 2, coffee: 6}
_Map<dynamic, dynamic> _Set<String>
false
true

Inside a collection literal you can write:

  • ...list, the spread operator, to insert all elements of another collection; ...?maybeList inserts nothing if the collection is null.
  • if (condition) element, optionally with else, to include an element conditionally.
  • for (... in ...) element to include one element per iteration.
  • ?expression, a null-aware element (since Dart 3.8), to include a value only if it is not null. Here special is 'pancakes' and is added, while forgotten is null and is skipped.

These forms nest, and they work in list, set and map literals alike: the expensive map is built with a for and an if in one expression. Compared with creating an empty list and calling add in a loop, the literal is shorter, can be assigned to a final variable in one step, and in Flutter, describes a widget tree as one expression.

Two pitfalls appear at the end of the program. {} on its own is an empty map (shown by its run-time type, which on the VM prints as _Map<dynamic, dynamic>), because maps came first; write a type argument, as in the set line, to get an empty set. And lists compare by identity: two separate lists with the same contents are not ==. Only constant lists, which the compiler canonicalizes into one object, compare equal. For contents equality, use ListEquality from the Dart team's collection package, or compare records, which do have value equality.

Worked examplesH

Iterables are lazy

Iterable is the interface for "something you can walk through with for-in". List and Set are iterables, and so are the results of map, where, skip, take and expand. Those methods are lazy: they return a description of a computation, and the computation runs only when something walks the result.

dart
void main() {
  final words = ['Kigali', 'Oslo', 'Tbilisi', 'Lima', 'Ulaanbaatar', 'Apia'];

  // map and where are lazy: nothing runs until the result is used.
  var calls = 0;
  final lengths = words.map((w) {
    calls++;
    return w.length;
  });
  print('calls so far: $calls');
  print(lengths.where((n) => n > 4).toList());
  print('calls after one pass: $calls');
  print(lengths.first);
  print('calls after asking for first: $calls');

  // Some useful Iterable methods.
  print(words.any((w) => w.startsWith('O')));
  print(words.every((w) => w.length >= 4));
  print(words.fold<int>(0, (total, w) => total + w.length));
  print(words.firstWhere((w) => w.length > 20, orElse: () => 'none'));
  print(words.skip(2).take(2).toList());
  print(words.expand((w) => [w[0], w.length]).take(6).toList());

  // indexed (Dart 3.0) pairs each element with its position as a record.
  for (final (i, w) in words.indexed.where((p) => p.$1.isEven)) {
    print('$i: $w');
  }

  // Grouping by a key with a map of lists.
  final byLength = <int, List<String>>{};
  for (final w in words) {
    (byLength[w.length] ??= []).add(w);
  }
  print(byLength);
}
text
calls so far: 0
[6, 7, 11]
calls after one pass: 6
6
calls after asking for first: 7
true
true
36
none
[Tbilisi, Lima]
[K, 6, O, 4, T, 7]
0: Kigali
2: Tbilisi
4: Ulaanbaatar
{6: [Kigali], 4: [Oslo, Lima, Apia], 7: [Tbilisi], 11: [Ulaanbaatar]}

The counter shows the laziness. Creating lengths ran the function zero times. Walking it once with where(...).toList() ran it six times, once per word. Asking for lengths.first ran it once more, because a lazy iterable recomputes every time it is walked. Two consequences follow. Never put side effects (printing, counting, saving) in a map function and expect them to happen once. And when you will walk a result several times, or the computation is expensive, call toList() once and keep the list.

The rest is a tour of methods you will use daily: any and every test elements; fold combines them with a starting value (here the total number of letters, 36); firstWhere with orElse avoids an exception when nothing matches; skip and take slice; expand maps each element to several. indexed (Dart 3.0) yields (index, element) records, and for (final (i, w) in ...) takes each record apart with a pattern; p.$1 reads a record's first positional field. Finally, (byLength[w.length] ??= []).add(w) is a compact grouping idiom: create the list for a key the first time it is needed, then add to it. The collection package offers groupBy for the same job.

Worked examplesH

Choosing a collection, and what it costs

dart
void main() {
  // List.generate builds each element with a function.
  final squares = List.generate(6, (i) => i * i);
  print(squares);

  // List.filled reuses ONE object for every slot: a classic trap with lists of lists.
  final shared = List.filled(3, <int>[]);
  shared[0].add(7);
  print(shared);
  final separate = List.generate(3, (_) => <int>[]);
  separate[0].add(7);
  print(separate);

  // An unmodifiable copy protects data you hand out.
  final frozen = List.unmodifiable(squares);
  try {
    frozen.add(36);
  } on UnsupportedError catch (e) {
    print(e.message);
  }

  // Membership: a list searches every element; a set hashes straight to the answer.
  final ids = List.generate(100000, (i) => i * 7);
  final idSet = ids.toSet();
  final watch = Stopwatch()..start();
  var found = 0;
  for (var k = 0; k < 2000; k++) {
    if (ids.contains(k * 350)) found++;
  }
  final listTime = watch.elapsedMicroseconds;
  watch.reset();
  for (var k = 0; k < 2000; k++) {
    if (idSet.contains(k * 350)) found++;
  }
  final setTime = watch.elapsedMicroseconds;
  print('found $found; the set was faster: ${setTime < listTime}');

  // whereType filters by type and gives a correctly typed result.
  final mixed = <Object>[1, 'two', 3.0, 4, 'five'];
  final ints = mixed.whereType<int>().toList();
  print('$ints ${ints.runtimeType}');
}
text
[0, 1, 4, 9, 16, 25]
[[7], [7], [7]]
[[7], [], []]
Cannot add to an unmodifiable list
found 4000; the set was faster: true
[1, 4] List<int>
  • List.generate(n, f) calls f for each index. List.filled(n, value) puts the same value in every slot, which is fine for numbers but a trap for mutable objects: all three slots of shared are one list, so adding to one adds to "all". Use generate to get separate objects.
  • List.unmodifiable makes a read-only copy; the check happens at run time, with an UnsupportedError. Returning unmodifiable collections (or the UnmodifiableListView wrapper from dart:collection) from a class stops callers from changing its internal state behind its back.
  • Cost. contains on a list compares elements one by one, so it takes time proportional to the length. A Set (and a Map's keys) uses hashing and answers in roughly constant time, which is why 2,000 lookups among 100,000 ids were much faster in the set. If you repeatedly ask "is this in here?", convert to a set once. Hashing relies on == and hashCode; the next lesson shows how to give your own classes both.
  • whereType keeps the elements of one type and gives the result that type, here a list of int, without casts.
Worked examplesH

Generics

Collections are generic: a list of strings and a list of ints share one implementation, with a type argument saying what they hold. The type argument usually comes from inference, and you write it explicitly, in angle brackets before a literal or after a type name, when there is nothing to infer from, as with empty collections. Your own functions and classes can be generic too.

dart
// A generic function: T is chosen by each call, and checked by the compiler.
T? mostCommon<T>(Iterable<T> items) {
  final counts = <T, int>{};
  for (final item in items) {
    counts[item] = (counts[item] ?? 0) + 1;
  }
  T? best;
  var bestCount = 0;
  counts.forEach((item, count) {
    if (count > bestCount) {
      best = item;
      bestCount = count;
    }
  });
  return best;
}

void main() {
  print(mostCommon([3, 1, 3, 2, 3, 1]));
  print(mostCommon('mississippi'.split('')));
  print(mostCommon(<double>[]));

  // Generic types are reified: the type argument exists at run time.
  final names = <String>['Ife', 'Juan'];
  final Object something = names;
  print(something is List<String>);
  print(something is List<int>);

  // Generic collections are covariant, which the runtime has to guard.
  final List<num> numbers = <int>[1, 2, 3];
  try {
    numbers.add(
      2.5,
    ); // allowed by the static type, but the list holds only ints
  } on TypeError catch (e) {
    print('TypeError: $e');
  }
}
text
3
i
null
true
false
TypeError: type 'double' is not a subtype of type 'int' of 'value'

mostCommon declares a type parameter T after its name and uses it for its argument, its map's keys and its result. Each call fixes T: int for the first, String for the second, double for the empty list, where the function returns null. Inside the function, a T can be stored, compared with == and used as a map key, which is all the function needs; a function that compared elements with < would declare a bound, T extends Comparable, much as Java does.

Dart's generics are reified: type arguments exist at run time, so an is test on something can really check that it is a list of strings and not a list of ints, which Java, with its erased generics, cannot. They are also covariant: a list of int may be used where a list of num is expected. That is convenient, but not statically sound, because through the num view you could add a double. Dart closes the hole at run time: the list knows it holds ints and throws a TypeError on the bad add, as the last line shows. Dart's designers accepted this trade-off for convenience, and in practice the problem is rare, but it is worth knowing why the error can happen.

ExplanationH

Collections in professional Dart

A few conventions recur in well-kept Dart codebases, most of them from Effective Dart. Use collection literals rather than constructors ([], not List(), which no longer exists anyway). Test emptiness with isEmpty and isNotEmpty rather than length == 0, which reads better and is faster for some iterables. Prefer a for-in loop to forEach with a function literal: the loop can break, await and return. Use whereType instead of filtering and casting. Store collections in final fields, expose them read-only, and give every empty literal an explicit type so the analyzer never infers dynamic. Finally, reach for the Dart team's collection package (deep equality, groupBy, firstWhereOrNull, priority queues) before writing your own utilities.

Common misconceptionsH

Common misconceptions

Misconception

"map returns a list." It returns a lazy Iterable. Printing it shows parentheses, indexing it is not possible, and walking it twice runs the function twice. Add toList() when you need a list.

Misconception

"{} is an empty set." It is an empty map. An empty set needs a type: a type argument before the braces, or a declared type such as Set of String on the variable.

Misconception

"Maps and sets have no order in Dart." The default implementations remember insertion order, so iteration and printing are predictable. If you want sorted order, use SplayTreeMap from dart:collection or sort the keys.

Misconception

"A spread or toList() copies everything." Both make a shallow copy: a new outer collection whose elements are the same objects. Nested lists, maps and mutable objects are still shared. For a deep copy you must copy each level yourself, or design your data with immutable objects so that sharing is harmless.

Misconception

"List.filled(3, []) gives me three empty lists." It gives one empty list, referenced three times. Use List.generate(3, (_) => []) with a type argument for separate lists.

Misconception

"list1 == list2 compares contents." It compares identity. Use a deep equality from package:collection, or records, for value comparison.

Exercises

Exercises

1. Collections and generics

CoreComputational

What does print(seating(false)); print?

String? plusOne(String name) => name == 'Bo' ? 'Cy' : null;

List<String> seating(bool vip) {
  final guests = ['Ana', 'Bo'];
  return [
    'Host',
    ...guests,
    if (vip) 'Press' else 'Public',
    for (final g in guests) ?plusOne(g),
  ];
}

2. Collections and generics

StretchComputational

What does this program print?

void main() {
  var calls = 0;
  final doubled = [1, 2, 3].map((n) {
    calls++;
    return n * 2;
  });
  doubled.toList();
  doubled.toList();
  print(doubled.first + calls);
}

3. Collections and generics

CoreComputational

What does this print?

final rows = List.filled(2, <String>[]);
rows[1].add('x');
print('${rows[0].length} ${rows.length}');

4. Collections and generics

CoreComputational

What does this print?

final counts = <String, int>{};
for (final w in 'to be or not to be'.split(' ')) {
  counts.update(w, (n) => n + 1, ifAbsent: () => 1);
}
print(counts);

5. Collections and generics

Warm-upComputational

What does print([3, 4, 5].fold<int>(1, (acc, n) => acc * n)); print?

6. Collections and generics

Warm-upHuman

What is final things = {};?

Choose one

7. Collections and generics

StretchComputational

What happens here?

final List<num> numbers = <int>[1, 2, 3];
numbers.add(2.5);
Choose one

Further reading and resources