Pattern matching
- Dart course
- Intermediate
- Lesson 73/116
- 5 min
Learn Dart 3 pattern matching and destructuring.
Destructure with pattern matching
Pattern matching splits a value into parts. In its simplest form it destructures a record: var (a, b) = (1, 2);. Now a is 1 and b is 2.
The same syntax splits a list: var [first, ...rest] = [10, 20, 30];. Here first is 10 and rest is [20, 30].
For a map you can write var {'name': name} = {'name': 'Dart'};. The pattern describes the structure; Dart binds variables when it matches.
List patterns
A list pattern splits the head and the tail. In var [first, ...rest] = [10, 20, 30]; first takes the head and rest takes the rest.
A fixed-length pattern also works: var [x, y] = [5, 9];. Here the list must have exactly two items.
If the pattern does not match Dart throws. So you use patterns on data whose structure you know.
Practice Destructure a record
In main destructure a record with var (a, b) = (3, 4);. Print the sum of a and b with print.
Starter code
void main() {
// destructure the (3, 4) record, print the sum
}Sample solution
void main() {
var (a, b) = (3, 4);
print(a + b);
}Expected output
7
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does var (a, b) = (1, 2); give?
- a = 1, b = 2 Correct answer
- a = 2, b = 1
- Compile error
- a = (1,2), b = empty
Explanation: The pattern matches left to right.
2 List head pattern
var [first, ____] = [10, 20, 30];
var [first, ...rest] = [10, 20, 30];
Explanation: ...rest captures all remaining items.
3 Pattern matching
| Term | Meaning |
|---|---|
var (a, b) = (1, 2); |
Record pattern |
var [x, ...rest] = list; |
List pattern |
var {'name': name} = m; |
Map pattern |