Dart Switch
Dart Switch
Instead of writing many if...else statements, you can use the switch statement.
The switch statement picks one of many code blocks to run:
switch (value) {
case a:
// code block
case b:
// code block
default:
// code block
}
This is how it works:
- Dart reads the
switchvalue once - It compares the value with each
case, from top to bottom - If there is a match, Dart runs the code of that case, and then leaves the
switch - If no case matches, Dart runs the
defaultcode, if there is one
A Switch Example
This example uses the weekday number to print the weekday name:
Example
void main() {
final day = 4;
switch (day) {
case 1:
print('Monday');
case 2:
print('Tuesday');
case 3:
print('Wednesday');
case 4:
print('Thursday');
case 5:
print('Friday');
case 6:
print('Saturday');
case 7:
print('Sunday');
}
}
Try it Yourself »
Result:
Thursday
Only "Thursday" is printed.
When a case has code, Dart stops after that code and does not run the next case.
So in Dart, you do not need a break at the end of each case.
Note: In languages like Java and C, a case without break "falls through" and runs the next case too.
Dart does not do this.
You may still write break, but it is not needed.
The default Keyword
The default keyword gives the code to run when no case matches:
Example
void main() {
final day = 9;
switch (day) {
case 6:
print('Today is Saturday');
case 7:
print('Today is Sunday');
default:
print('Looking forward to the weekend');
}
}
Try it Yourself »
Result:
Looking forward to the weekend
The default case must be the last case in the switch.
Cases That Share Code
An empty case, a case with no code, uses the code of the next case.
This lets several values share the same code:
Example
void main() {
final day = 'Sunday';
switch (day) {
case 'Saturday':
case 'Sunday':
print('Weekend');
default:
print('Weekday');
}
}
Try it Yourself »
Result:
Weekend
You can also put several values in one case with ||, which means "or":
Example
void main() {
final fruit = 'lemon';
switch (fruit) {
case 'apple' || 'cherry' || 'strawberry':
print('$fruit is red');
case 'banana' || 'lemon':
print('$fruit is yellow');
default:
print('I do not know the color of $fruit');
}
}
Try it Yourself »
Result:
lemon is yellow
Switch With Strings
The switch value can be a number, a string, or many other types.
Each case runs as many statements as you need:
Example
void main() {
final command = 'start';
switch (command) {
case 'start':
print('Starting the engine...');
print('The car is running.');
case 'stop':
print('Stopping the engine...');
print('The car is parked.');
default:
print('Unknown command: $command');
}
}
Try it Yourself »
Result:
Starting the engine...
The car is running.
Switch Expressions
Dart also has a switch expression, a shorter form of switch that gives back a value.
You will learn about it in the Dart Switch Expressions chapter.