Dart Switch Expressions
Dart Switch Expressions
In the Switch chapter, you learned the switch statement, which runs different code for different values.
Dart 3 also has a switch expression.
An expression is code that gives a value, so a switch expression gives you a result that you can store in a variable, return or print.
Each case is written as pattern => result, and the cases are separated by commas:
Example
void main() {
var day = 3;
var name = switch (day) {
1 => 'Monday',
2 => 'Tuesday',
3 => 'Wednesday',
4 => 'Thursday',
5 => 'Friday',
6 => 'Saturday',
7 => 'Sunday',
_ => 'Invalid day',
};
print(name);
}
Try it Yourself »
Result:
Wednesday
Example Explained
- The value in the parentheses,
day, is compared with each case from top to bottom. - The first case that matches is used, and its result becomes the value of the whole switch.
- The wildcard
_matches any value, so it works likedefaultin a switch statement. - There is no
casekeyword, no colon, and nobreak. - The whole switch ends with a semicolon, because it is part of the statement
var name = ...;.
Here is the same program written with a switch statement, so you can compare:
Example
void main() {
var day = 3;
String name;
switch (day) {
case 1:
name = 'Monday';
case 2:
name = 'Tuesday';
case 3:
name = 'Wednesday';
case 4:
name = 'Thursday';
case 5:
name = 'Friday';
case 6:
name = 'Saturday';
case 7:
name = 'Sunday';
default:
name = 'Invalid day';
}
print(name);
}
Try it Yourself »
Result:
Wednesday
The switch expression is shorter, and you do not need to assign the variable in every case.
| Switch statement | Switch expression | |
|---|---|---|
| Gives a value | No | Yes |
| Case syntax | case 1: | 1 => |
| Default case | default: | _ => |
| Each case can have | Many statements | One expression |
| Best for | Doing things | Choosing a value |
Exhaustiveness
A switch expression must always give a value.
That is why Dart checks that the cases cover every possible value.
This check is called exhaustiveness checking.
An int has a huge number of possible values, so without the _ case, this program does not run:
Example
void main() {
var day = 3;
var name = switch (day) {
1 => 'Monday',
2 => 'Tuesday',
3 => 'Wednesday',
};
print(name);
}
Try it Yourself »
Result:
main.dart:4:22: Error: The type 'int' is not exhaustively matched by the switch cases since it doesn't match 'int()'.
Try adding a wildcard pattern or cases that match 'int()'.
var name = switch (day) {
^
With an enum or a bool, Dart knows all the possible values.
If you list them all, you do not need _:
Example
enum Light { red, yellow, green }
void main() {
var light = Light.yellow;
var action = switch (light) {
Light.red => 'Stop',
Light.yellow => 'Wait',
Light.green => 'Go',
};
print(action);
}
Try it Yourself »
Result:
Wait
Tip: Leave out _ when you can.
If you add a new value to the enum later, Dart shows an error for every switch that forgets it.
Logical-or Patterns
Use || between patterns when several values should give the same result.
This is called a logical-or pattern:
Example
String dayType(String day) {
return switch (day) {
'Sat' || 'Sun' => 'Weekend',
'Mon' || 'Tue' || 'Wed' || 'Thu' || 'Fri' => 'Weekday',
_ => 'Unknown',
};
}
void main() {
print(dayType('Sun'));
print(dayType('Tue'));
print(dayType('Abc'));
}
Try it Yourself »
Result:
Weekend
Weekday
Unknown
Relational Patterns
A relational pattern compares the value with a comparison operator, like >=, < or ==.
This is perfect for ranges, like turning a score into a grade:
Example
String grade(int score) {
return switch (score) {
>= 90 => 'A',
>= 80 => 'B',
>= 70 => 'C',
>= 60 => 'D',
_ => 'F',
};
}
void main() {
print(grade(95));
print(grade(83));
print(grade(42));
}
Try it Yourself »
Result:
A
B
F
The cases are checked from top to bottom, so a score of 95 gets 'A' and never reaches the other cases.
Use && to combine two relational patterns into a range:
Example
String ageGroup(int age) {
return switch (age) {
< 0 => 'Invalid',
>= 0 && <= 12 => 'Child',
>= 13 && <= 19 => 'Teenager',
_ => 'Adult',
};
}
void main() {
print(ageGroup(8));
print(ageGroup(16));
print(ageGroup(45));
}
Try it Yourself »
Result:
Child
Teenager
Adult
Guards with when
A guard is an extra condition for a case.
You write it after the pattern with the keyword when.
The case only matches if the pattern matches and the condition is true:
Example
String describe((String, int) product) {
return switch (product) {
(var name, var stock) when stock == 0 => '$name is sold out',
(var name, var stock) when stock < 5 => 'Only $stock $name left',
(var name, _) => '$name is in stock',
};
}
void main() {
print(describe(('Apple', 0)));
print(describe(('Banana', 3)));
print(describe(('Cherry', 50)));
}
Try it Yourself »
Result:
Apple is sold out
Only 3 Banana left
Cherry is in stock
In this example, each case is a record pattern, from the Patterns chapter.
The pattern unpacks the record into name and stock, and the guard checks the stock.
Note: Dart does not look inside a guard when it checks exhaustiveness.
That is why the last case has no guard, so that every product is covered.