Destructuring

suggest change

Destructuring means taking a composite value (a record, list, map or object) apart and binding its pieces to local variables in one step. Dart got destructuring in Dart 3.0 as part of patterns. Before that, you had to write one line per field:

final point = getPoint();
final x = point.x;
final y = point.y;

With patterns, you write the shape of the data on the left side and Dart pulls out the parts:

final Point(:x, :y) = getPoint();

This article covers destructuring in variable declarations, assignments, loops, switch and if-case. For matching and exhaustiveness checks in general, see Pattern matching.

All examples require Dart 3.0 or newer (set sdk: ^3.0.0 or higher in pubspec.yaml).

Records

Records are the most common thing to destructure, because they're how Dart functions return multiple values.

Positional fields

A record pattern lists one subpattern per positional field:

(String, int) parseLine(String line) {
  final parts = line.split(':');
  return (parts[0].trim(), int.parse(parts[1]));
}

void main() {
  final (name, score) = parseLine('alice: 42');
  print('$name scored $score'); // alice scored 42
  print(name.runtimeType); // String
  print(score.runtimeType); // int
}

The variables get their types from the record type (String, int), so name is a String and score is an int. You don't need annotations.

The pattern must have the same shape as the record. final (a, b) = (1, 2, 3); is a compile-time error because the record has 3 fields and the pattern has 2.

Named fields

For named fields, write name: pattern. When the variable has the same name as the field, use the shorthand :name:

({String host, int port}) parseAddress(String s) {
  final i = s.lastIndexOf(':');
  return (host: s.substring(0, i), port: int.parse(s.substring(i + 1)));
}

void main() {
  // Variables named differently from the fields.
  final (host: h, port: p) = parseAddress('example.com:8080');
  print('$h / $p'); // example.com / 8080

  // Shorthand: variables named after the fields.
  final (:host, :port) = parseAddress('localhost:5432');
  print('$host / $port'); // localhost / 5432
}

Records can mix positional and named fields, and so can the pattern:

void main() {
  final record = (1, 2, label: 'origin');
  final (x, y, :label) = record;
  print('$label = ($x, $y)'); // origin = (1, 2)
}

Swapping and pattern assignment

Destructuring also works on existing variables, without var or final. This is called a pattern assignment. The classic use is swapping two values without a temporary variable:

void main() {
  var a = 'left';
  var b = 'right';
  (a, b) = (b, a);
  print('$a $b'); // right left

  // Assign multiple results to existing variables.
  int min, max;
  (min, max) = minMax([5, 3, 9, 1]);
  print('min=$min max=$max'); // min=1 max=9
}

(int, int) minMax(List<int> xs) {
  var lo = xs.first, hi = xs.first;
  for (final x in xs) {
    if (x < lo) lo = x;
    if (x > hi) hi = x;
  }
  return (lo, hi);
}

The right side is evaluated fully before any variable is assigned, which is why the swap works.

Lists

A list pattern destructures a List by position:

void main() {
  final rgb = [255, 128, 0];
  final [r, g, b] = rgb;
  print('r=$r g=$g b=$b'); // r=255 g=128 b=0
}

A list pattern without a rest element matches only lists of exactly that length. In a declaration, Dart can't check the length at compile time, so a mismatch throws at runtime:

void main() {
  final values = [1, 2, 3, 4];
  try {
    final [a, b] = values; // list has 4 elements, pattern expects 2
    print('$a $b');
  } catch (e) {
    print('Error: ${e.runtimeType}');
  }
}

If the length isn't guaranteed, use if-case (shown later) instead of a declaration.

Rest elements

... matches any number of elements. Put a variable after it to collect them into a new list:

void main() {
  final numbers = [10, 20, 30, 40, 50];

  final [first, second, ...rest] = numbers;
  print('$first $second $rest'); // 10 20 [30, 40, 50]

  final [head, ...middle, last] = numbers;
  print('$head $middle $last'); // 10 [20, 30, 40] 50

  // Without a name, the rest is skipped.
  final [x, ...] = numbers;
  print(x); // 10

  final [..., y, z] = numbers;
  print('$y $z'); // 40 50
}

A pattern can have at most one rest element. With a rest element, the list only needs to be at least as long as the other subpatterns.

List patterns only match List. To destructure a Set or another Iterable, convert it with .toList() first.

Ignoring values with _

The wildcard _ matches anything and binds nothing. Use it for elements or fields you don't need. You can use it more than once in the same pattern:

void main() {
  final parts = '2026-10-17'.split('-');
  final [year, _, _] = parts;
  print(year); // 2026

  final (_, port, _) = ('tcp', 443, true);
  print(port); // 443
}

Maps

A map pattern lists keys (which must be constants) and a pattern for each value:

void main() {
  final config = {'host': 'db.local', 'port': '5432', 'user': 'admin'};

  final {'host': host, 'port': port} = config;
  print('$host:$port'); // db.local:5432
}

Unlike list patterns, map patterns ignore extra keys. Here 'user' is in the map but not in the pattern, and that's fine.

A key that's missing from the map makes the match fail. In a declaration that's a runtime error, so for data you don't control (JSON, user input) use if-case, which checks keys and value types together:

import 'dart:convert';

void main() {
  final inputs = [
    '{"name": "Alice", "age": 30}',
    '{"name": "Bob"}',
    '{"name": "Carol", "age": "unknown"}',
  ];

  for (final input in inputs) {
    final json = jsonDecode(input);
    if (json case {'name': String name, 'age': int age}) {
      print('$name is $age');
    } else {
      print('Invalid: $input');
    }
  }
}

Output:

Alice is 30
Invalid: {"name": "Bob"}
Invalid: {"name": "Carol", "age": "unknown"}

String name and int age are typed variable patterns: in a refutable context like if-case they check the type and fail the match if it's wrong, so no as casts are needed. See JSON for more on parsing JSON.

Objects

An object pattern destructures any class through its getters. The syntax looks like a constructor call, but it reads fields instead of creating an object:

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

void main() {
  const p = Point(3, 4);

  final Point(x: px, y: py) = p;
  print('$px, $py'); // 3, 4

  final Point(:x, :y) = p;
  print('$x, $y'); // 3, 4
}

The class doesn't need any special support: any getter works, including computed ones and getters on built-in types:

void main() {
  final date = DateTime(2026, 10, 17, 14, 30);
  final DateTime(:year, :month, :day, :weekday) = date;
  print('$year-$month-$day, weekday $weekday'); // 2026-10-17, weekday 6

  final String(:length, :isEmpty) = 'hello';
  print('$length $isEmpty'); // 5 false

  final uri = Uri.parse('https://example.com:8443/api/users?page=2');
  final Uri(:scheme, :host, :port, :path, :queryParameters) = uri;
  print('$scheme $host $port $path $queryParameters');
  // https example.com 8443 /api/users {page: 2}
}

In a declaration, the matched value must already have the type named in the object pattern. final Point(:x) = someObject; where someObject is an Object is a compile-time error. Use if-case or switch to test the type first.

Nested patterns

Patterns nest freely, so you can take apart a deeply structured value in a single declaration:

class Line {
  final Point start;
  final Point end;
  const Line(this.start, this.end);
}

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

void main() {
  const line = Line(Point(0, 0), Point(3, 4));
  final Line(start: Point(x: x1, y: y1), end: Point(x: x2, y: y2)) = line;
  print('from ($x1, $y1) to ($x2, $y2)'); // from (0, 0) to (3, 4)

  final data = (id: 7, tags: ['dart', 'patterns', 'records']);
  final (:id, tags: [firstTag, ...otherTags]) = data;
  print('$id $firstTag $otherTags'); // 7 dart [patterns, records]
}

Keep nested patterns readable: if a pattern spans more than a line or two, splitting it into a couple of declarations is often clearer.

Destructuring in for loops

The variable in a for-in loop can be a pattern. This is useful with Map.entries, lists of records and indexed:

void main() {
  final scores = {'alice': 95, 'bob': 82, 'carol': 77};

  // MapEntry has `key` and `value` getters.
  for (final MapEntry(:key, :value) in scores.entries) {
    print('$key: $value');
  }

  // Rename while destructuring.
  for (final MapEntry(key: name, value: score) in scores.entries) {
    if (score > 80) print('$name passed');
  }

  // `indexed` yields (index, element) records.
  final fruits = ['apple', 'banana', 'cherry'];
  for (final (i, fruit) in fruits.indexed) {
    print('$i: $fruit');
  }

  // A list of records.
  final points = [(1, 2), (3, 4), (5, 6)];
  var sum = 0;
  for (final (x, y) in points) {
    sum += x * y;
  }
  print('sum = $sum');
}

Output:

alice: 95
bob: 82
carol: 77
alice passed
bob passed
0: apple
1: banana
2: cherry
sum = 44

Destructuring in switch and if-case

In a declaration, the pattern must always match (it's irrefutable). In switch and if-case, patterns can fail (they're refutable), so you can combine destructuring with checks on types, values and lengths.

if-case

if (value case pattern) runs the body only when the pattern matches, with the destructured variables in scope:

void printCommand(List<String> args) {
  if (args case ['copy', final from, final to]) {
    print('copy $from -> $to');
  } else if (args case ['delete', final file, ...]) {
    print('delete $file');
  } else {
    print('unknown: $args');
  }
}

void main() {
  printCommand(['copy', 'a.txt', 'b.txt']);
  printCommand(['delete', 'old.log', '--force']);
  printCommand(['copy', 'a.txt']);
}

Output:

copy a.txt -> b.txt
delete old.log
unknown: [copy, a.txt]

Note that in refutable patterns, you mark new variables with final or var (or a type), because a bare identifier like copy would be a constant to compare against.

switch expressions

A switch expression can destructure and compute a result in each case. A when guard adds an extra condition:

sealed class Shape {}

class Circle extends Shape {
  final double radius;
  Circle(this.radius);
}

class Rect extends Shape {
  final double width, height;
  Rect(this.width, this.height);
}

String describe(Shape shape) => switch (shape) {
      Circle(:final radius) when radius == 0 => 'a point',
      Circle(:final radius) => 'circle, area ${(3.14159 * radius * radius).toStringAsFixed(2)}',
      Rect(:final width, :final height) when width == height => 'square ${width}x$width',
      Rect(:final width, :final height) => 'rectangle ${width}x$height',
    };

void main() {
  print(describe(Circle(0))); // a point
  print(describe(Circle(2))); // circle, area 12.57
  print(describe(Rect(3, 3))); // square 3.0x3.0
  print(describe(Rect(2, 5))); // rectangle 2.0x5.0
}

In a refutable context the shorthand is :final radius (or :var radius, or :double radius), not just :radius.

Switching on a record built on the spot is a neat way to destructure and match several values together:

String fizzBuzz(int n) => switch ((n % 3, n % 5)) {
      (0, 0) => 'FizzBuzz',
      (0, _) => 'Fizz',
      (_, 0) => 'Buzz',
      _ => '$n',
    };

void main() {
  print([for (var i = 1; i <= 15; i++) fizzBuzz(i)].join(' '));
  // 1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz
}

Casts and null assertions in declarations

Two refutable-looking patterns are allowed in declarations because they throw instead of failing:

import 'dart:convert';

(String?, int?) lookup(String key) => (key, key.length);

void main() {
  // jsonDecode returns dynamic; cast each element while destructuring.
  final [x as int, y as int] = jsonDecode('[10, 20]') as List;
  print(x + y); // 30

  // Strip nullability from record fields.
  final (name!, length!) = lookup('dart');
  print('${name.toUpperCase()} $length'); // DART 4
}

Use these when a wrong value is a bug. When it's an expected case (such as invalid user input), use if-case with typed patterns or the null-check pattern ?, which are refutable and only allowed in if-case and switch:

void main() {
  final (String?, int?) maybe = (null, 3);
  if (maybe case (final name?, final count?)) {
    print('$name x $count');
  } else {
    print('missing data'); // printed, because name is null
  }
}

What Dart doesn't destructure

A few things that work in other languages don't work in Dart:

Function parameters. You can't write a pattern in a parameter list (void f((int, int) (x, y)) isn't valid). Destructure in the first line of the body instead:

double distanceSquared((double, double) a, (double, double) b) {
  final (x1, y1) = a;
  final (x2, y2) = b;
  final dx = x2 - x1, dy = y2 - y1;
  return dx * dx + dy * dy;
}

void main() {
  print(distanceSquared((0, 0), (3, 4))); // 25.0
}

The same applies to closures: list.map(((a, b)) => a + b) isn't valid. Write list.map((p) { final (a, b) = p; return a + b; }), or use the record fields $1 and $2 directly:

void main() {
  final pairs = [(1, 2), (3, 4)];
  print(pairs.map((p) => p.$1 + p.$2).toList()); // [3, 7]
  print(pairs.map((p) => switch (p) { (final a, final b) => a * b }).toList()); // [2, 12]
}

Refutable patterns in declarations. Constants, relational patterns (> 0), type tests without a cast, and ? can fail, so they're compile-time errors in var/final declarations:

// final (0, y) = point;         // error: constant pattern can fail
// final [int a, int b] = objs;  // error: objs is a List<Object>
// final (name?, _) = record;    // error: null-check pattern can fail

Setters and mutation. Destructuring copies values into new variables. Changing those variables doesn't change the original object, and object patterns only call getters.

Summary

Data Declaration Refutable (if-case, switch)
Positional record final (a, b) = r; case (final a, 0)
Named record final (:name, :age) = r; case (name: final n, age: >= 18)
List final [a, b, ...rest] = xs; case [final a, ...]
Map final {'k': v} = m; case {'k': String v}
Object final Point(:x, :y) = p; case Point(:final x, y: 0)
Existing variables (a, b) = (b, a); n/a

Use declarations when the shape is guaranteed by the static types (records, your own classes). Use if-case or switch when the data might not match, such as lists of unknown length, maps from JSON and values of a supertype.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents