Dart Patterns
Dart Patterns
A pattern describes the shape of a value.
Dart can use a pattern in two ways:
- To destructure a value, which means to unpack its parts into separate variables.
- To match a value, which means to check if the value has a certain shape.
Patterns work with records, lists, maps and objects.
Note: Patterns were added in Dart 3, together with records.
Destructure a Record
In the Records chapter, we used $1 and $2 to get the fields of a record.
With a pattern, you can unpack all the fields into variables in one line:
Example
void main() {
var car = ('Volvo', 2020);
var (brand, year) = car;
print('$brand, $year');
var person = (name: 'Liam', age: 30);
var (:name, :age) = person;
print('$name is $age years old');
}
Try it Yourself »
Result:
Volvo, 2020
Liam is 30 years old
The pattern (brand, year) has the same shape as the record, so the first field goes into brand and the second field goes into year.
For named fields, the pattern :name gets the field name into a variable with the same name.
If you want a different variable name, write name: variable, like var (name: personName, age: personAge) = person;.
This is very useful when a function returns a record:
Example
(int, int) minMax(List<int> numbers) {
var sorted = [...numbers]..sort();
return (sorted.first, sorted.last);
}
void main() {
var (low, high) = minMax([7, 2, 9, 4]);
print('Lowest: $low');
print('Highest: $high');
}
Try it Yourself »
Result:
Lowest: 2
Highest: 9
Destructure Lists and Maps
A list pattern is written with square brackets [].
It unpacks the items of a list in order:
Example
void main() {
var scores = [90, 75, 60];
var [first, second, third] = scores;
print('$first, $second, $third');
var fruits = ['Apple', 'Banana', 'Cherry', 'Mango'];
var [favorite, ...others] = fruits;
print(favorite);
print(others);
}
Try it Yourself »
Result:
90, 75, 60
Apple
[Banana, Cherry, Mango]
Without ..., the list must have exactly as many items as the pattern.
The ...others part is called a rest element, and it collects the remaining items into a new list.
A map pattern is written with curly brackets {}, and gets the values of the keys you name.
Other keys in the map are ignored:
Example
void main() {
var user = {'name': 'Emma', 'city': 'Oslo', 'age': 25};
var {'name': name, 'city': city} = user;
print('$name lives in $city');
}
Try it Yourself »
Result:
Emma lives in Oslo
The Wildcard _
Sometimes you only need some of the values.
Use the wildcard _ for a value you do not need.
The wildcard matches any value, but does not create a variable:
Example
void main() {
var car = ('Volvo', 2020, 'red');
var (brand, _, color) = car;
print('$brand, $color');
var [winner, _, _] = ['Anna', 'Liam', 'Emma'];
print('Winner: $winner');
}
Try it Yourself »
Result:
Volvo, red
Winner: Anna
Match a Value with if-case
When you destructure a list with var, the list must have the right length, or the program stops with an error.
When you are not sure about the shape, use if with case.
The code in the if block only runs if the value matches the pattern:
Example
void main() {
var point = [3, 5];
if (point case [var x, var y]) {
print('x is $x and y is $y');
}
var numbers = [1, 2, 3];
if (numbers case [var a, var b]) {
print('Two numbers');
} else {
print('Not two numbers');
}
}
Try it Yourself »
Result:
x is 3 and y is 5
Not two numbers
Patterns like var x are called variable patterns, because they put the matched value into a new variable.
A variable pattern can also have a type, like String name.
Then it only matches values of that type.
This is a safe way to read data where you do not know the types, like a map from a file or a web server:
Example
void main() {
Map<String, Object> data = {'name': 'Liam', 'age': 30};
if (data case {'name': String name, 'age': int age}) {
print('$name is $age years old');
} else {
print('Data is not valid');
}
Map<String, Object> bad = {'name': 'Liam', 'age': 'thirty'};
if (bad case {'name': String name, 'age': int age}) {
print('$name is $age years old');
} else {
print('Data is not valid');
}
}
Try it Yourself »
Result:
Liam is 30 years old
Data is not valid
Patterns in for-in Loops
You can use a pattern in a for-in loop, to unpack each item as you go.
Here, each item in the list is a record:
Example
void main() {
var scores = [('Anna', 90), ('Liam', 75), ('Emma', 82)];
for (var (name, score) in scores) {
print('$name: $score');
}
}
Try it Yourself »
Result:
Anna: 90
Liam: 75
Emma: 82
Object Patterns
An object pattern matches an object of a class, and gets the values of its getters or fields.
You write the class name, and then the fields in parentheses.
Just like with named fields in records, :x gets the field x into a variable called x:
Example
class Point {
final int x;
final int y;
Point(this.x, this.y);
}
void main() {
var p = Point(3, 7);
var Point(:x, :y) = p;
print('x: $x, y: $y');
}
Try it Yourself »
Result:
x: 3, y: 7
Object patterns are often used in loops.
Each entry of a map is a MapEntry object with a key and a value:
Example
void main() {
var prices = {'Apple': 1.5, 'Banana': 0.5, 'Cherry': 3.0};
for (var MapEntry(:key, :value) in prices.entries) {
print('$key costs $value');
}
}
Try it Yourself »
Result:
Apple costs 1.5
Banana costs 0.5
Cherry costs 3.0
Tip: Patterns are even more powerful in switch expressions, which you will learn about in the next chapter.