Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 73 ยท Dart essentials

Collections and Generics

Master Dart collections for Flutter: List, Map and Set, spread, collection if and for, map/where/fold, generics, records, patterns, sealed classes and switch.

Lists of items drive most Flutter screens: a list of messages, a map of settings, a set of selected ids. Dart's collection types are easy to use, and a few special syntaxes, such as collection if and the spread operator, make widget code short and readable. This lesson also introduces generics, records, patterns and sealed classes, the modern tools that make state handling in Flutter safe.

Dart code is read-only on this site. JavaScript TryIts act as stand-ins for the data transformations, which behave very similarly.

List, Set and Map

Three core collections

List Ordered, indexed, duplicates allowed.
Set Unique items, fast contains.
Map Key to value pairs.

The element types are part of the collection's type, for example List<String>.

1 / 2
DART
final names = <String>['Ada', 'Grace', 'Linus'];     // List<String>
final ids = {3, 5, 5, 8};                             // Set<int>, holds 3, 5, 8
final stock = {'apples': 4, 'pears': 0};              // Map<String, int>

names.add('Margaret');
print(names[0]);               // Ada
print(names.length);           // 4
print(ids.contains(5));        // true
stock['plums'] = 12;
print(stock['pears']);         // 0
print(stock['kiwi']);          // null - reading a missing key gives null

A map lookup returns a nullable value (int?), because the key might not exist. Handle it with ??, as covered in Null Safety:

DART
final kiwis = stock['kiwi'] ?? 0;

List literals are growable by default. const [1, 2, 3] and List.unmodifiable(x) make lists that cannot change; List.filled(3, 0) creates a fixed-length list.

Generics

The <...> after a type name is a type argument. A generic class works with a type chosen by the user, and the compiler checks it:

DART
final numbers = <int>[1, 2, 3];
numbers.add('four');            // compile error: String is not an int

class Box<T> {
  final T value;
  const Box(this.value);
}

final intBox = Box<int>(5);
final textBox = Box('hi');      // T inferred as String

Flutter uses generics everywhere: Future<String>, State<MyWidget>, ValueNotifier<int>, Navigator.push<bool>. You can also restrict a type parameter: class Sorter<T extends Comparable<T>>.

Spread, collection if and collection for

These three features are made for building UI children lists:

DART
final base = [1, 2, 3];
final more = [0, ...base, 4];                  // spread: [0, 1, 2, 3, 4]

final loggedIn = true;
final menu = [
  'Home',
  'Search',
  if (loggedIn) 'Profile',                      // collection if
  if (!loggedIn) ...['Login', 'Register'],
];

final squares = [for (var i = 1; i <= 4; i++) i * i];   // [1, 4, 9, 16]

In a widget tree these look like this (read-only Flutter code):

DART
Column(
  children: [
    const Text('Messages'),
    if (messages.isEmpty) const Text('Nothing yet'),
    for (final message in messages) Text(message),
  ],
)

No temporary lists, no addAll loops: the structure of the code matches the structure of the UI.

Working with data: map, where, fold

Collections have higher-order methods that take functions:

DART
final prices = [4.5, 12.0, 3.25, 9.0];

final cheap = prices.where((p) => p < 10).toList();          // [4.5, 3.25, 9.0]
final labels = prices.map((p) => '\$$p').toList();           // ['$4.5', ...]
final total = prices.fold<double>(0, (sum, p) => sum + p);   // 28.75
final anyFree = prices.any((p) => p == 0);                   // false
final first = prices.firstWhere((p) => p > 10, orElse: () => -1);

Important detail: map and where return lazy iterables, not lists. Call .toList() when you need a list, for example to pass children to a widget. Other helpful methods are sort, reversed, take, skip, expand, every, reduce and indexed (pairs of index and value).

The same pipeline in JavaScript is almost identical, so you can experiment with the logic here:

JS where, map and fold, JavaScript version

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Records and patterns

A record groups several values into one lightweight, immutable value without declaring a class:

DART
(String, int) fetchUser() => ('Ada', 31);

({String name, int age}) fetchNamed() => (name: 'Ada', age: 31);

void main() {
  final (name, age) = fetchUser();          // destructuring pattern
  final user = fetchNamed();
  print('$name is $age');
  print(user.name);                          // named fields
}

Records are perfect for returning two values from a function. Patterns let you match and take apart values in switch, if-case and variable declarations:

DART
final json = {'type': 'circle', 'radius': 2.0};

if (json case {'type': 'circle', 'radius': double r}) {
  print('Circle with radius $r');
}

final [first, ...rest] = [1, 2, 3];          // first = 1, rest = [2, 3]

Sealed classes and exhaustive switch

A sealed class can only be extended in its own library, so the compiler knows all its subclasses. A switch over a sealed type must handle each one, or it does not compile. This is a great fit for screen states:

DART
sealed class LoadState {}

class Loading extends LoadState {}

class Loaded extends LoadState {
  final List<String> items;
  Loaded(this.items);
}

class Failed extends LoadState {
  final String message;
  Failed(this.message);
}

String describe(LoadState state) => switch (state) {
  Loading() => 'Please wait',
  Loaded(:final items) when items.isEmpty => 'No items',
  Loaded(:final items) => '${items.length} items',
  Failed(:final message) => 'Error: $message',
};

If you add a fourth subclass and forget to handle it in describe, the analyzer reports an error, not a runtime surprise. You will use exactly this style for loading, data and error states in FutureBuilder, StreamBuilder and Async UI.

JavaScript has no sealed classes, but a tagged object and a function with a lookup table behave similarly. The stand-in below also adds a guard that throws on an unknown tag, which is the check Dart does at compile time:

JS A sealed state, imitated with tags

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does stock['kiwi'] return when the map has no 'kiwi' key?

    A missing key gives null, so the result type is nullable (for example int?). Use ?? to add a default.
  2. 2. Why call .toList() after map(...) before passing the result to a widget's children?

    map and where return lazy iterables. Widgets expect a List, so convert with toList().
  3. 3. What does [0, ...base, 4] do?

    The spread operator ... inserts every element of another collection.
  4. 4. What is the benefit of a sealed class combined with a switch?

    A sealed class has a known set of subclasses, so a switch must be exhaustive and the analyzer flags missing cases.

Summary

  • List, Set and Map are the core collections; element types are part of the type (List<int>).
  • Map lookups are nullable; combine them with ??.
  • Spread (...), collection if and collection for build lists declaratively, ideal for widget children.
  • where, map and fold transform data; remember .toList().
  • Records return several values; patterns destructure and match.
  • Sealed classes with switch expressions give exhaustive, compile-checked state handling.
  • Dart blocks are read-only; the TryIts are JavaScript stand-ins.

Next: More Dart: Comments, Numbers, Input, Enums and Accessors