Sub topic 12
Records, patterns, and switch expressions
This chapter assumes you know Dart variables, functions, collections, and classes, including sealed classes. It covers records, which bundle several values into one, and patterns, which test and take apart values. It also covers switch expressions, which use patterns to pick a result. All of it needs Dart 3 or later.
Records: lightweight value bundles
A record is an anonymous, immutable, fixed-size group of values. Write it with parentheses. Fields can be positional, named, or both.
void main() {
final point = (3, 4);
final person = (name: 'Ada', age: 36);
final mixed = (1, 'two', flag: true);
print(point.$1);
print(person.name);
print(mixed.$2);
print(mixed.flag);
print((1, 2) == (1, 2));
}Positional fields are read with $1, $2, and so on. The numbering counts only positional fields, so mixed.$2 is 'two' even though a named field exists. Named fields are read by name.
Records have structural equality. Two records are equal when they have the same shape and equal field values. For named fields, the order you write them in does not matter. The last line above prints true, and no == override is needed.
Record types
A record type mirrors the literal syntax. Named fields go inside braces.
(int, int) origin = (0, 0);
({String name, int age}) person = (name: 'Ada', age: 36);
(double min, double max) bounds(List<double> values) {
var lo = values.first;
var hi = values.first;
for (final v in values) {
if (v < lo) lo = v;
if (v > hi) hi = v;
}
return (lo, hi);
}The names in (double min, double max) are documentation only. Callers still read the fields as $1 and $2, or destructure them. The most common use of a record is returning several values from a function without writing a class for them.
Records have limits. You cannot add methods to them or make them extend anything. A field name cannot start with an underscore, and it cannot clash with members such as hashCode or toString. When the data needs behavior or a name of its own, use a class.
Patterns and destructuring
A pattern describes the shape a value should have. It can also bind parts of that value to new variables. Matching is allowed in four places: variable declarations, assignments, switch, and if-case.
void main() {
final person = (name: 'Ada', age: 36);
final (name: n, age: a) = person;
final (:name, :age) = person;
print('$n $a $name $age');
var x = 1;
var y = 2;
(x, y) = (y, x);
print('$x $y');
final [first, second, ...rest] = [10, 20, 30, 40];
print('$first $second $rest');
}The :name form is shorthand for name: name, so the variable takes the field's name. The assignment (x, y) = (y, x) swaps two variables without a temporary. List patterns can end with a rest element (...), and it can bind the leftover items as shown.
Refutable and irrefutable patterns
An irrefutable pattern always matches. Declarations and assignments accept only these, and a failed match there would be a compile-time error. A refutable pattern may fail to match. switch cases and if-case accept these, and when one fails, execution moves on.
| Pattern | Example | Matches when | Column | Column |
|---|---|---|---|---|
| Constant | `0`, `'x'`, `Planet.mars` | The value equals the constant | ||
| Relational | `> 3`, `<= 10` | The comparison is true | ||
| Logical-or / and | `1 \ | \ | 2`, `> 3 && < 100` | Either side / both sides match |
| Variable | `var n`, `int n` | Always (typed form checks the type) | ||
| Wildcard | `_` | Always, binds nothing | ||
| Null-check / assert | `int n?`, `n!` | Non-null / throws on null | ||
| Cast | `n as int` | Casts, throws if the cast fails | ||
| List | `[a, ...]` | Length and elements fit | ||
| Map | `{'k': v}` | The key exists and the value matches | ||
| Record | `(a, b: c)` | Same shape, fields match | ||
| Object | `Circle(:var r)` | The type matches, then getters match |
Switch expressions
A switch expression produces a value. It has no case keyword, no break, and each arm has the form pattern => result,.
String describe(int n) => switch (n) {
0 => 'zero',
1 || 2 || 3 => 'small',
> 3 && < 100 => 'medium',
>= 100 => 'large',
_ => 'negative',
};
String quadrant((int, int) p) => switch (p) {
(0, 0) => 'origin',
(> 0, > 0) => 'first',
(< 0, > 0) => 'second',
(< 0, < 0) => 'third',
(> 0, < 0) => 'fourth',
_ => 'on an axis',
};
void main() {
print(describe(50));
print(quadrant((2, -5)));
}Arms are tested from top to bottom, and the first match wins. The expression must be exhaustive, meaning every possible input must be covered. In both functions the final _ arm covers whatever is left. If no arm matches at runtime, Dart throws an error.
Guards
Add a when clause to a case for an extra boolean test. The case matches only if the pattern matches and the guard is true.
String parity(Object o) => switch (o) {
int n when n.isEven => 'even int',
int _ => 'odd int',
String s when s.isEmpty => 'empty string',
String _ => 'string',
_ => 'other',
};Here int n when n.isEven binds n and tests it. The next arm, int _, catches the remaining integers.
Exhaustiveness with sealed classes and enums
Exhaustiveness checking works best on sealed classes and enums. The compiler knows every subtype, so no _ arm is needed. If you later add a subtype, every switch that lacks a case for it stops compiling.
sealed class Shape {}
class Circle extends Shape {
final double r;
Circle(this.r);
}
class Rect extends Shape {
final double w;
final double h;
Rect(this.w, this.h);
}
double area(Shape s) => switch (s) {
Circle(:var r) => 3.14159 * r * r,
Rect(:var w, :var h) => w * h,
};
void main() {
print(area(Rect(2, 3)));
}Circle(:var r) is an object pattern. It checks that s is a Circle, then reads the r getter into a new variable.
Switch statements
The statement form still uses case and :. In Dart 3 it no longer falls through, so break is optional. An empty case body is the one way to share a body between cases. Statement switches over sealed types and enums must also be exhaustive, and the same pattern syntax works.
if-case and nested patterns
When you only care about one shape, if-case is lighter than a switch. It is also the usual way to read loosely typed data such as decoded JSON.
void main() {
final json = {
'name': 'Ada',
'langs': ['dart', 'c'],
};
if (json case {'name': String name, 'langs': [String first, ...]}) {
print('$name starts with $first');
} else {
print('unexpected shape');
}
}The map pattern checks that both keys exist. It also checks that name is a String, and that langs is a non-empty list whose first item is a String. Variables bound in the pattern are in scope only in the if branch. A map pattern ignores extra keys. A list pattern without ... requires the exact length.
Common errors
- Refutable pattern in a declaration.
final [a, b] = items;compiles. Ifitemsdoes not have exactly two elements, it throws at runtime. To handle other lengths, useif-caseor aswitch. - Old switch syntax in an expression. Writing
case 1:orbreakinside a switch expression is a syntax error. Use=>and commas. - Missing exhaustiveness. A switch over
Object,int, orStringneeds a_arm. Only sealed types, enums, andboolcan be exhausted without one. - Unreachable arms. Placing
_or a broad type first makes later arms dead code, and the analyzer warns you. Order cases from most specific to least specific. - Expecting a
Mappattern to be strict.{'a': 1}still matches{'a': 1, 'b': 2}. - Treating records as classes. If you keep adding fields or want methods, switch to a class. Record fields are always read by position or name, and the type has no way to hold behavior.
Exercise
Write a function String classify(({String kind, int size}) item) that returns 'big box' when kind is 'box' and size is above 10, 'box' for any other box, and 'unknown' otherwise. Use a switch expression with a record pattern and a guard.
Show answer
String classify(({String kind, int size}) item) => switch (item) { (kind: 'box', size: var s) when s > 10 => 'big box', (kind: 'box', size: ) => 'box', => 'unknown', };
Exercise
A sealed class Result has subclasses Ok(int value) and Err(String message). Why can String show(Result r) => switch (r) { Ok(:var value) => '$value', Err(:var message) => message }; omit a _ arm, and what happens if you add class Pending extends Result {} later?
Show answer
Because Result is sealed, the compiler knows Ok and Err are the only subtypes, so the two arms cover every value. After you add Pending, the switch is no longer exhaustive and the code fails to compile until you add a Pending arm or a _ arm.