Dart Switch
A switch statement matches one value against a list of cases. The case that matches runs its block.
Matching a number
The value 2 matches the second case. The screen shows the name of that day.
void main() {
var day = 2;
switch (day) {
case 1:
print('Monday');
break;
case 2:
print('Tuesday');
break;
case 3:
print('Wednesday');
break;
}
}Matching a piece of text
The stored text matches the apple case. The screen shows the line from that case.
void main() {
var fruit = 'apple';
switch (fruit) {
case 'apple':
print('Red fruit');
break;
case 'banana':
print('Yellow fruit');
break;
}
}The default case
The value 9 matches no numbered case. The default block runs instead.
void main() {
var day = 9;
switch (day) {
case 1:
print('Monday');
break;
case 2:
print('Tuesday');
break;
default:
print('Another day');
}
}Example
void main() {
var light = 'green';
switch (light) {
case 'red':
print('Stop');
break;
case 'yellow':
print('Slow down');
break;
case 'green':
print('Move');
break;
default:
print('No signal');
}
}Key points
- Use switch to pick a block by matching one value.
- The value sits in round brackets after the word switch.
- Use case to name one value to match.
- Use break to end a case block.
- Use default for the block that runs when no case matches.
- A switch can match a whole number or a piece of text.
In this example, light holds the text green. The switch tests the red case first and finds no match. The yellow case also misses. The green case matches, so its block prints Move. The default block never runs.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท DartPad
Exercise
Which case runs when no other case matches?