Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 61 ยท Control Flow

Patterns and Destructuring

Learn Dart 3 patterns: destructure lists, maps, records and objects, use if-case and switch, and know the main pattern types, with runnable stand-ins.

A pattern describes the shape of a value. Dart 3 can use a pattern in two ways: to match (does this value have this shape?) and to destructure (take the value apart and bind its pieces to variables). Patterns appear in variable declarations, assignments, for-in loops, if-case statements and switch.

Patterns replace a lot of repetitive code, such as reading list[0], list[1], checking lengths, or testing the type of a JSON value before using it. You already met simple patterns in switch statements and expressions. This lesson covers the rest.

The Dart snippets are read-only. Dart is not installed on the site, so the TypeScript stand-ins show the matching logic with destructuring syntax that TypeScript also has, written by hand where TypeScript lacks a feature.

Destructuring in declarations

The simplest use is a declaration. Instead of a single name on the left of =, write a pattern:

DART
void main() {
  var (x, y) = (3, 4);          // record pattern
  var [first, second] = [10, 20]; // list pattern
  print('$x $y $first $second');  // 3 4 10 20
}

The right side is taken apart and each variable gets its piece. If the shape does not fit (for example the list has three elements instead of two), a declaration throws at run time, so use it when you are sure.

Patterns also swap variables without a temporary:

DART
void main() {
  var a = 1, b = 2;
  (a, b) = (b, a);
  print('$a $b'); // 2 1
}

The right side builds a record (2, 1) and the left side assigns it back to the two variables.

TypeScript Destructuring and swapping (stand-in)

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

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Records

Records were introduced in Records, and they destructure in two ways, by position and by name.

DART
(String, int) userInfo() => ('Ada', 36);

({String name, int age}) namedInfo() => (name: 'Ada', age: 36);

void main() {
  final (name, age) = userInfo();
  print('$name is $age');

  final (name: n, age: a) = namedInfo();
  print('$n is $a');
}

When the variable should have the same name as the field, use the shorthand :name, as in final (:name, :age) = namedInfo();. It means "the field name, bound to a variable also called name".

List patterns

A list pattern matches a list of an exact length, unless it contains a rest element ....

DART
String describe(List<int> list) {
  return switch (list) {
    [] => 'empty',
    [var only] => 'one item: $only',
    [var a, var b] => 'two items: $a and $b',
    [var head, ...var tail] => 'starts with $head, then ${tail.length} more',
  };
}

void main() {
  print(describe([]));
  print(describe([7]));
  print(describe([1, 2]));
  print(describe([1, 2, 3, 4]));
}
TEXT
empty
one item: 7
two items: 1 and 2
starts with 1, then 3 more

The rest element can sit anywhere, but only once: [var first, ..., var last] matches any list with at least two elements and binds the first and last. Use ...var rest to capture the middle as a new list, or a plain ... to ignore it.

TypeScript List patterns (stand-in)

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

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Map patterns

A map pattern matches a map that contains the given keys. Keys must be constants. Extra keys are allowed, and values can have their own patterns.

DART
void main() {
  final config = {'host': 'localhost', 'port': 8080, 'debug': true};

  if (config case {'host': String host, 'port': int port}) {
    print('Connect to $host:$port');
  }
}

If either key is missing or has the wrong type, the pattern fails and the if branch is skipped. That makes map patterns excellent for checking decoded JSON before using it, since the type test and the extraction happen in one step.

if-case

if (value case pattern) { ... } tests one pattern. If it matches, the variables it declares are available inside the block. An optional guard can follow:

DART
void main() {
  final data = [3, 'three'];

  if (data case [int number, String word] when number > 0) {
    print('$number is spelled "$word"');
  } else {
    print('Not the shape I expected');
  }
}

Use if-case instead of a full switch when you care about a single shape. You can also use case in a collection if, which allows a list literal to include an element only when a value fits.

flowchart LR
    V["Value"] --> P{"Does it match<br/>the pattern?"}
    P -->|"yes"| B["Bind variables<br/>and run the block"]
    P -->|"no"| E["Skip or go to else"]

A refutable pattern either matches and binds variables, or fails and the code moves on.

TypeScript Checking the shape of data (stand-in)

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

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Object patterns

An object pattern matches by type and reads getters (including fields) by name:

DART
class Point {
  final int x;
  final int y;
  const Point(this.x, this.y);
}

String where(Point p) => switch (p) {
      Point(x: 0, y: 0) => 'origin',
      Point(x: 0) => 'on the y axis',
      Point(y: 0) => 'on the x axis',
      Point(x: var px, y: var py) => 'at $px, $py',
    };

Point(x: 0) means "a Point whose x getter equals 0". The last arm binds both coordinates. If the variable name equals the getter name, shorten it: Point(:var x, :var y).

Object patterns work with any class, including built-in ones. MapEntry(key: var k, value: var v) takes apart a map entry, and Rect(width: > 100) combines an object pattern with a relational pattern.

The pattern toolbox

You have seen several kinds already. Here is the overview:

Pattern Example Meaning
Constant 42, 'go', Light.red Equal to this value
Variable var n, final n, int n Match (optionally of a type) and bind
Wildcard _ Match anything, bind nothing
Relational > 10, != 0 Compare with a constant
Logical-or 1 || 2 Either sub-pattern
Logical-and int n && > 0 Both sub-patterns
Cast n as int Cast, throws if it fails
Null-check var n? Match non-null and bind
Null-assert var n! Throws if null
List [a, ..., b] A list with this shape
Map {'k': v} A map with these keys
Record (a, b), (x: a) A record with this shape
Object Point(x: 0) An instance of a type, reading getters

The wildcard also lets you ignore parts you do not need, as in var (_, second) = pair;.

Refutable and irrefutable patterns

A pattern in a plain declaration (var (a, b) = ...) is irrefutable: it is expected to match, and a mismatch is an error. In if-case and switch the pattern is refutable: failing to match is a normal outcome that leads to the next case or the else branch. A few patterns, such as constants, are only allowed in the refutable positions.

Destructuring in loops

Because a for-in loop declares a variable, it can take a pattern as well:

DART
void main() {
  final scores = {'Ada': 92, 'Linus': 85};
  for (final MapEntry(key: name, value: score) in scores.entries) {
    print('$name scored $score');
  }
}
TypeScript Object-style matching and map entries (stand-in)

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

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does (a, b) = (b, a); do when a and b are existing variables?

    The right side creates a record with the swapped values, and the pattern on the left assigns them back to a and b.
  2. 2. When does if (config case {'host': String host}) run its block?

    A map pattern needs the listed keys, and the nested String pattern checks the value's type. Extra keys are allowed.
  3. 3. What does [var first, ..., var last] match?

    The rest element stands for any number of items in the middle, including none, so at least two elements are needed.
  4. 4. What is the difference between an irrefutable and a refutable pattern?

    if-case and switch use refutable patterns and move on when they fail. A plain declaration expects the pattern to match.

Summary

  • Patterns match shapes and bind variables; they work in declarations, assignments, for-in, if-case and switch.
  • Record, list, map and object patterns destructure values; _ ignores a part, ... stands for the rest of a list.
  • if (value case pattern) tests one shape, with optional when guard.
  • Map patterns are ideal for checking decoded JSON.
  • Variable, constant, relational, logical, cast and null patterns combine with the structural ones.

Next: functions.