The Dart 3 features
Dart 3.0, released in May 2023, added three features that work together and changed how idiomatic Dart looks. Records are lightweight, anonymous groups of values, perfect for returning two things from a function. Patterns describe the shape of a value, so that one line can check that a value is a list of two numbers, or a map with a 'name' string, and pull the parts out into variables. Sealed classes declare a closed family of types, so that the compiler can check that a switch handles every member of the family.
Together they bring to Dart what functional programmers call algebraic data types with pattern matching, the same ideas behind Swift's enums with associated values, Rust's enums and Kotlin's sealed classes. They make it practical to model data so that impossible states cannot be represented, and to have the compiler tell you every place that needs updating when the model grows.
Records
Definition— record
A record is an immutable, fixed-size, anonymous aggregate of values. Its fields can be positional, read as $1, $2 and so on, or named, read by name. Its type is written like the value, for example (int, int) or ({double lat, double lon}). Two records are equal when they have the same shape and equal fields.
// A function can return several values as a record.
(int, int)? bounds(List<int> numbers) {
if (numbers.isEmpty) return null;
var low = numbers.first, high = numbers.first;
for (final n in numbers) {
if (n < low) low = n;
if (n > high) high = n;
}
return (low, high);
}
// Named fields make the meaning clear at the use site.
({double lat, double lon}) cityCentre(String city) => switch (city) {
'Quito' => (lat: -0.18, lon: -78.47),
_ => (lat: 0, lon: 0),
};
void main() {
final b = bounds([8, -2, 15, 4]);
print(b);
if (b != null) print('${b.$1} to ${b.$2}');
// Destructuring with a record pattern.
if (bounds([5, 9, 7]) case (final low, final high)) {
print('range ${high - low}');
}
final quito = cityCentre('Quito');
print('${quito.lat}, ${quito.lon}');
final (:lat, :lon) =
quito; // the :name shorthand binds a variable called name
print(lat + lon);
// Records have value equality and can be map keys.
print((1, 'a') == (1, 'a'));
final seats = {(row: 3, seat: 'C'): 'Ikram', (row: 1, seat: 'A'): 'Dawit'};
print(seats[(row: 3, seat: 'C')]);
// Swapping with a pattern assignment.
var x = 1, y = 2;
(x, y) = (y, x);
print('$x $y');
}(-2, 15)
-2 to 15
range 4
-0.18, -78.47
-78.65
true
Ikram
2 1bounds returns (int, int)?: a pair, or null for an empty list. The call site can read the fields as $1 and $2, but more often takes the record apart with a pattern, as the if (... case (final low, final high)) line does. Named fields, as in cityCentre, make the meaning visible; final (:lat, :lon) = quito declares variables named after the fields. Because records compare by value, they work as map keys and in sets without writing == and hashCode, and (x, y) = (y, x) swaps two variables in one line.
When should you use a record and when a class? Records are best for small, local groupings: multiple return values, temporary pairs, keys. Once a grouping gets a name, behaviour, documentation or a place in a public API, a class (perhaps with a primary constructor) communicates better.
Patterns
Definition— pattern
A pattern is a description of the shape of a value. Matching a value against a pattern checks whether the value has that shape, and, if so, destructures it, binding parts of it to new variables. Patterns appear in variable declarations, assignments, for-in loops, switch statements and expressions, and if (expression case pattern).
String classify(Object? value) => switch (value) {
null => 'nothing',
0 => 'zero',
int n when n < 0 => 'a negative int',
int() && > 100 => 'a big int',
int _ => 'a small positive int',
String(isEmpty: true) => 'an empty string',
String s => 'text of length ${s.length}',
[] => 'an empty list',
[final only] => 'a list holding just $only',
[final first, ..., final last] => 'a list from $first to $last',
(num x, num y) => 'a point at ($x, $y)',
_ => 'something else',
};
void main() {
const samples = [
null,
0,
-7,
250,
42,
'',
'Bamako',
[],
[9],
[1, 2, 3],
(2, 3.5),
true,
];
for (final s in samples) {
print('${'$s'.padRight(9)} ${classify(s)}');
}
// Patterns check the shape of data, such as decoded JSON, in one step.
final responses = <Object?>[
{
'name': 'Leila',
'age': 31,
'tags': ['admin', 'ops'],
},
{'name': 'Tomás', 'age': '31'},
{'name': 'Yuki'},
];
for (final json in responses) {
if (json case {'name': String name, 'age': int age}) {
print('$name is $age');
} else {
print('invalid record: $json');
}
}
}null nothing
0 zero
-7 a negative int
250 a big int
42 a small positive int
an empty string
Bamako text of length 6
[] an empty list
[9] a list holding just 9
[1, 2, 3] a list from 1 to 3
(2, 3.5) a point at (2, 3.5)
true something else
Leila is 31
invalid record: {name: Tomás, age: 31}
invalid record: {name: Yuki}classify is a tour of the pattern kinds, tried in order, first match wins:
| Pattern | Example | Matches |
|---|---|---|
| constant | null, 0 | a value equal to the constant |
| variable, with type | int n, String s | a value of that type, bound to the name |
| wildcard | _, int _ | anything (of that type), binding nothing |
| guard | int n when n < 0 | only if the condition after when holds |
| object | int(), String(isEmpty: true) | a value of that type whose getters match the subpatterns |
| relational | > 100 | a value for which the comparison is true |
| logical | int() && > 100, 6 || 7 | both subpatterns, or either |
| list | [], [final only], [final first, ..., final last] | lists of that length; ... is a rest element |
| record | (num x, num y) | records of that shape |
| map | {'name': String name} | maps containing those keys with matching values |
The second half shows the most common practical use: validating decoded JSON, which arrives as untyped maps and lists. The single pattern {'name': String name, 'age': int age} checks that the value is a map, that it has both keys, and that their values have the right types, and binds name and age as a String and an int. Tomás's age arrived as a string and Yuki's is missing, so both are rejected. Without patterns, that check is a tangle of is tests and casts. Map patterns ignore extra keys such as tags; list patterns, by contrast, must match the length unless they contain a rest element.
Refutable and irrefutable patterns
Patterns behave differently depending on where they appear. In a switch case or an if-case, a pattern is refutable: if the value does not match, that case is simply skipped. In a variable declaration, an assignment or a for-in loop, there is no "otherwise", so the pattern is expected to match:
final results = [('Aroha', 91), ('Bashir', 78)];
for (final (name, score) in results) {
print('$name: $score'); // Aroha: 91, then Bashir: 78
}
final [first, second] = 'Lagos Abuja'.split(' ');
print(second); // Abuja
final [a, b] = 'one two three'.split(' '); // three words, two variablesThe record pattern in the loop and the first list pattern fit their values, but the last declaration fails at run time with Bad state: Pattern matching error, because a list of three elements does not match a two-element list pattern. The compiler accepts it because the length of a list is not known statically. That is what the Money.parse factory in the previous lesson relied on: valid input splits into exactly two parts. For data you do not control, use a refutable if-case or switch and handle the mismatch, and keep declaration patterns for values whose shape you are sure of, such as records returned by your own functions, whose shape the type system does guarantee.
Enums and sealed classes
Patterns become most powerful when the compiler knows every possible type a value can have. Dart offers two ways to declare such a closed set.
Enums list a fixed set of instances. Since Dart 2.17, enhanced enums can have fields, constructors (which must be const), getters and methods, and implement interfaces. Sealed classes list a fixed set of subtypes, each of which can carry different data, the same idea as Swift's enums with associated values.
// An enhanced enum (Dart 2.17): cases with fields, a constructor and methods.
enum Size {
small(250),
medium(350),
large(500);
const Size(this.millilitres);
final int millilitres;
bool get isLarge => this == large;
}
// A sealed class: every subtype is known, so a switch over it can be exhaustive.
sealed class Payment {
const Payment();
}
class Cash extends Payment {
const Cash();
}
class Card extends Payment {
final String last4;
const Card(this.last4);
}
class MobileMoney extends Payment {
final String provider;
final String phone;
const MobileMoney(this.provider, this.phone);
}
class Voucher extends Payment {
final String code;
final int cents;
const Voucher(this.code, this.cents);
}
String receipt(Payment payment, int total) => switch (payment) {
Cash() => 'Paid $total cents in cash',
Card(:final last4) => 'Card ending $last4 charged $total cents',
MobileMoney(:final provider, :final phone) => '$provider payment from $phone',
Voucher(:final code, :final cents) when cents >= total =>
'Voucher $code covers it all',
Voucher(:final code, :final cents) =>
'Voucher $code covers $cents; ${total - cents} cents due',
};
void main() {
for (final size in Size.values) {
print(
'${size.name}: ${size.millilitres} ml${size.isLarge ? ' (large!)' : ''}',
);
}
print(Size.values.byName('medium').index);
const payments = <Payment>[
Cash(),
Card('4417'),
MobileMoney('M-Pesa', '+254 700 000 000'),
Voucher('EID25', 2500),
Voucher('SMALL', 300),
];
for (final p in payments) {
print(receipt(p, 1200));
}
}small: 250 ml
medium: 350 ml
large: 500 ml (large!)
1
Paid 1200 cents in cash
Card ending 4417 charged 1200 cents
M-Pesa payment from +254 700 000 000
Voucher EID25 covers it all
Voucher SMALL covers 300; 900 cents dueSize gives each case a millilitres field through a const constructor; Size.values lists the cases, name gives a case's name and byName looks one up. Payment is sealed: it is implicitly abstract, and its direct subtypes may only be declared in the same library, so the compiler knows the complete list: Cash, Card, MobileMoney and Voucher. Each carries exactly the data it needs.
receipt switches over the payment with object patterns, such as Card(:final last4), which checks the type and binds the field in one step, and splits Voucher in two with a when guard. There is no default and no _ case, and none is needed: the compiler checks that the cases cover every subtype. Delete the MobileMoney line and the program does not compile:
Error: The type 'Payment' is not exhaustively matched by the switch cases since it doesn't match 'MobileMoney()'.That error is the point. When a fifth payment method is added next year, every switch that handles payments becomes a compile error until it handles the new case, so nothing slips through to production. A catch-all _ case would silence that check, so leave it out of switches over your own sealed types.
Switch statements, expressions and if-case
A switch expression (switch (x) { pattern => value, ... }) produces a value and must be exhaustive. A switch statement (switch (x) { case pattern: ... }) runs code; since Dart 3 it never falls through from a non-empty case, and it must be exhaustive when switching over an enum or a sealed type. if (value case pattern) tests a single pattern, optionally with when, and is the idiomatic replacement for an is check followed by casts. Pattern variables declared with final (or var) are scoped to the case or the if body.
Worked example: expressions as a sealed family
Example— Evaluating and simplifying arithmetic
A sealed family can be recursive: an expression is a number, a variable, or a sum or product of two smaller expressions. Each function over it is one switch, with one case per kind of node.
sealed class Expr {}
class Num extends Expr {
final double value;
Num(this.value);
}
class Var extends Expr {
final String name;
Var(this.name);
}
class Add extends Expr {
final Expr left, right;
Add(this.left, this.right);
}
class Mul extends Expr {
final Expr left, right;
Mul(this.left, this.right);
}
double evaluate(Expr e, Map<String, double> env) => switch (e) {
Num(:final value) => value,
Var(:final name) =>
env[name] ?? (throw ArgumentError('unbound variable $name')),
Add(:final left, :final right) => evaluate(left, env) + evaluate(right, env),
Mul(:final left, :final right) => evaluate(left, env) * evaluate(right, env),
};
String show(Expr e) => switch (e) {
Num(:final value) =>
value == value.roundToDouble() ? '${value.toInt()}' : '$value',
Var(:final name) => name,
Add(:final left, :final right) => '(${show(left)} + ${show(right)})',
Mul(:final left, :final right) => '${show(left)} * ${show(right)}',
};
// Nested patterns recognise algebraic shortcuts in one line each.
Expr simplify(Expr e) => switch (e) {
Add(left: Num(value: 0), :final right) => simplify(right),
Add(:final left, right: Num(value: 0)) => simplify(left),
Mul(left: Num(value: 0), right: _) ||
Mul(left: _, right: Num(value: 0)) => Num(0),
Mul(left: Num(value: 1), :final right) => simplify(right),
Mul(:final left, right: Num(value: 1)) => simplify(left),
Add(:final left, :final right) => Add(simplify(left), simplify(right)),
Mul(:final left, :final right) => Mul(simplify(left), simplify(right)),
Num() || Var() => e,
};
void main() {
// 1 * (x + 0) + 2 * y
final e = Add(Mul(Num(1), Add(Var('x'), Num(0))), Mul(Num(2), Var('y')));
final env = {'x': 4.0, 'y': 2.5};
print('${show(e)} = ${evaluate(e, env)}');
final s = simplify(e);
print('${show(s)} = ${evaluate(s, env)}');
print(show(simplify(Mul(Var('z'), Add(Num(0), Num(0))))));
}(1 * (x + 0) + 2 * y) = 9.0
(x + 2 * y) = 9.0
z * 0evaluate and show follow the shape of the data and are checked for exhaustiveness. In evaluate, ?? (throw ...) uses the fact that throw is an expression in Dart, so an unbound variable is reported with a clear error. simplify shows what nested patterns can do: Add(left: Num(value: 0), :final right) matches "a sum whose left side is the number zero" and keeps the right side, all in one line, and || lets one case cover both orders of Mul with a zero. The last case, Num() || Var() => e, handles the leaves.
The third line of output reveals a real bug, the kind that tests catch. Simplifying z * (0 + 0) gives z * 0, not 0, because the rules are checked against the original children; the right side becomes 0 only after the zero-product rule has already been passed over. The fix is to simplify bottom-up: first simplify both children, then match the rules against the simplified node. Exercise 7 asks you to think it through.
Modelling with sealed types
Flutter developers use sealed classes for exactly the situations where a value is "one of these, each with its own data": the state of a screen (Loading, Loaded(items), Failed(error)), the events a user can trigger, the result of a network call (Success(data) or Failure(error)), the nodes of a parsed document. The pattern is so common that state-management libraries in the Flutter ecosystem are built around it.
A useful habit is to ask, for every class with several nullable fields and a "type" or "status" field, whether it is really a sealed family in disguise. A Payment class with String? last4, String? provider and int? voucherCents permits eight combinations of present and missing fields, most of them nonsense; the sealed version permits exactly four shapes, each complete. Code that consumes it needs no defensive checks, and the compiler keeps it complete. Functional programmers call the principle making illegal states unrepresentable.
Common misconceptions
Misconception
"A record is just an untyped tuple, like a Python tuple." Records are statically typed: (int, String) and (String, int) are different types, and so are records with different field names. They are also immutable and compare by value.
Misconception
"A map pattern requires the map to have exactly those keys." It requires at least those keys, with matching values. Extra keys are ignored. List patterns, on the other hand, must match the length unless they contain a rest element ....
Misconception
"A guarded case covers its pattern." For exhaustiveness, the compiler ignores cases that have a when guard, because the guard might be false. That is why receipt needs a second, unguarded Voucher case: delete it and the compiler reports that Payment is not exhaustively matched since it doesn't match Voucher().
Misconception
"Sealed classes are the same as abstract classes." A sealed class is abstract, but it also closes its family: subtypes must be in the same library. That closure is what lets the compiler prove a switch exhaustive. An ordinary abstract class can be extended anywhere, so a switch over it always needs a fallback case.
Exercises
1. Records, patterns and sealed classes
CoreComputationalWhat does this program print?
void main() {
final a = (1, name: 'x');
final b = (1, name: 'x');
final c = (name: 'x', 1);
print('${a == b} ${a == c} ${a.$1 + 1} ${a.name}');
}
2. Records, patterns and sealed classes
CoreComputationalWhat does this program print?
String f(Object o) => switch (o) {
[int a, int b] when a > b => 'desc',
[int _, int _] => 'pair',
[_, ...] => 'list',
int n when n.isEven => 'even',
_ => 'other',
};
void main() {
print([[3, 1], [1, 3], [1], 4, 5].map(f).join(' '));
}
3. Records, patterns and sealed classes
CoreComputationalDoes if (json case {'id': int id}) match when json is {'id': 7, 'extra': true}?
4. Records, patterns and sealed classes
Warm-upComputationalWhat does this program print?
enum Spice {
mild(1),
medium(3),
hot(5),
fiery(8);
const Spice(this.heat);
final int heat;
}
void main() {
final total = [Spice.hot, Spice.mild, Spice.mild].fold(0, (s, x) => s + x.heat);
print('$total ${Spice.hot.index} ${Spice.values.last.name}');
}
5. Records, patterns and sealed classes
CoreComputationalWhat does this print?
var (p, q, r) = (1, 2, 3);
(p, q, r) = (r, p, q);
print(p * 100 + q * 10 + r);
6. Records, patterns and sealed classes
CoreHumanPayment is a sealed class, and receipt switches over it with one case per subtype and no _ case. A colleague adds class BankTransfer extends Payment in the same library. What happens?
7. Records, patterns and sealed classes
StretchHumanIn the worked example, simplify(Mul(Var('z'), Add(Num(0), Num(0)))) returns z * 0 instead of 0. Which change fixes it in general?
Further reading and resources
- Records
- Patterns
- Pattern typesThe full catalogue of patterns, with precedence.
- Branches (switch and if-case)
- Class modifiers (sealed)
- Enumerated types