Patterns & Destructuring
A pattern describes the shape of a value. Dart 3 uses patterns in many places — variable declarations, assignments, for loops, if-case and switch — to do two things at once:
- Match: test whether a value has a certain shape (type, length, constant, range…).
- Destructure: pull pieces out of the value and bind them to new variables.
Destructuring declarations
The left side of a declaration can be a pattern. It must match (the compiler checks that), and it creates one variable per binding:
class Point {
final int x, y;
const Point(this.x, this.y);
}
void main() {
// Record pattern
var (lat, lng) = (10.77, 106.70);
print('lat $lat, lng $lng');
// List pattern with a rest element
var [first, second, ...others] = [5, 10, 15, 20, 25];
print('$first $second $others');
// Map pattern
final {'name': name, 'role': role} = {'name': 'Tuyet', 'role': 'admin'};
print('$name is $role');
// Object pattern: reads getters by name
final Point(:x, :y) = const Point(3, 7);
print('x=$x y=$y');
// Wildcard _ ignores a value
final (_, status) = ('ignored', 200);
print(status);
}lat 10.77, lng 106.7
5 10 [15, 20, 25]
Tuyet is admin
x=3 y=7
200
The pattern catalogue
| Pattern | Example | Matches when… |
|---|---|---|
| Constant | 42, 'ok', null, Color.red |
value == constant |
| Variable | var n, final String s, int n |
always (typed version: if the type matches) |
| Wildcard | _, int _ |
always (or if the type matches) |
| Relational | > 0, <= limit |
comparison is true |
| Logical-and | int n && > 0 |
both subpatterns match |
| Logical-or | 'y' || 'yes' |
either subpattern matches |
| Cast | var n as int |
always — throws if the cast fails |
| Null-check | var v? |
value isn't null; binds the non-null value |
| Null-assert | var v! |
always — throws if null |
| Record | (a, b), (:name, age: var a) |
it's a record of that shape |
| List | [a, b], [first, ...], [..., last] |
it's a list of matching length/elements |
| Map | {'id': int id} |
it's a map containing those keys (others ignored) |
| Object | Point(x: 0, :y) |
it's that type and the getters match |
| Parenthesized | (> 0 && < 10) |
grouping |
Refutable patterns in if-case and switch
Patterns that might not match (refutable) are used where failure is handled — if-case and switch. This makes parsing loosely-typed data (like decoded JSON) both safe and readable:
String describe(Map<String, Object?> json) {
if (json case {'type': 'user', 'name': String name, 'age': int age} when age >= 18) {
return 'adult user $name';
}
if (json case {'type': 'user', 'name': String name}) {
return 'user $name';
}
if (json case {'type': 'product', 'tags': [String firstTag, ...]}) {
return 'product tagged $firstTag';
}
return 'unrecognised';
}
void main() {
print(describe({'type': 'user', 'name': 'Phat', 'age': 34}));
print(describe({'type': 'user', 'name': 'Bin', 'age': 12}));
print(describe({'type': 'product', 'tags': ['eco', 'new']}));
print(describe({'type': 'product', 'tags': []}));
print(describe({'name': 42}));
}adult user Phat
user Bin
product tagged eco
unrecognised
unrecognised
Compare that with the old way: checking json['name'] is String, casting, checking json['tags'] is List, checking its length… Patterns compress all of it into one declarative line.
Nested patterns
Patterns compose. Here a list of records of objects is unpacked in one go:
class Order {
final String id;
final List<(String, int)> lines;
Order(this.id, this.lines);
}
void main() {
final orders = [
Order('A1', [('pho', 2), ('tea', 1)]),
Order('B7', []),
Order('C3', [('cake', 5)]),
];
for (final order in orders) {
switch (order) {
case Order(lines: []):
print('${order.id}: empty');
case Order(:var id, lines: [(var item, var qty)]):
print('$id: just $qty x $item');
case Order(:var id, lines: [(var item, _), ...var rest]):
print('$id: $item and ${rest.length} more');
}
}
}A1: pho and 1 more
B7: empty
C3: just 5 x cake
Patterns in for loops and assignments
void main() {
final scores = {'Lan': 9, 'Vinh': 7};
for (final MapEntry(key: student, value: mark) in scores.entries) {
print('$student: $mark');
}
final pairs = [(1, 'one'), (2, 'two')];
for (final (n, word) in pairs) {
print('$n -> $word');
}
var lo = 5, hi = 1;
if (lo > hi) (lo, hi) = (hi, lo); // pattern assignment swaps
print('$lo..$hi');
}Lan: 9
Vinh: 7
1 -> one
2 -> two
1..5
Irrefutable vs refutable
| Context | Pattern must… | Example |
|---|---|---|
var/final declaration, assignment, for-in |
always match (irrefutable) | var (a, b) = pair; |
if (x case …), switch case, collection if-case |
may fail (refutable) | case [int a, int b]: |
A declaration such as var [a, b] = someList; is accepted because a List<T> always type-matches the list pattern — but if the list doesn't have exactly two elements at runtime, the program throws. When the data is untrusted, use if-case instead and handle the failed match.
Tip: Patterns shine at boundaries: JSON, command-line arguments, messages between isolates. Validate the shape once with a pattern, then work with strongly typed variables.
Test yourself
What does the map pattern {'id': int id} require?
- The map has exactly one key
- The map has an 'id' key whose value is an int (other keys allowed)
- The map is empty
- Any map
In final Point(:x, :y) = p;, what does :x do?
- Calls a method x()
- Reads the
xgetter and binds it to a variable named x - Declares a named parameter
- Casts p to x
Which context accepts refutable patterns (patterns that may not match)?
- var declarations
- for-in loops
- switch cases and if-case
- pattern assignments