Dart
switch with enum
Learn branching on enums with switch.
switch and enum
To branch on an enum you use switch. Each case catches a constant and runs the related code. Using switch on an enum is more readable than many ifs; the compiler also checks that all constants are handled.
Example: switch (status) { case Status.active: print("running"); break; case Status.idle: print("waiting"); break; }. After each case you need break to exit. Otherwise the compiler warns. Dart 3 also adds switch expressions; we will see them in the next lesson.
Exhaustive switch
When switching on an enum, handling all constants is called exhaustive. In Dart, if you cover every constant with a case, default is not required. If you add a new constant later, the compiler walks all cases and warns about the missing one; a big safety net.
You can still add a default; it is useful if constants may be added later or the value comes from an external source. With a default the compiler will not warn about new constants, so writing all of them out is often preferred. When all constants are listed you can also use return or a value expression instead of break.
Exercise Your turn: switch on Status
Define an enum Status with active, idle, maintenance. In main assign final s = Status.maintenance; and use a switch to print "under maintenance" for maintenance. Add a message for the other constants too; break after each case.
Show example solution
enum Status { active, idle, maintenance }
void main() {
final s = Status.maintenance;
switch (s) {
case Status.active:
print("running");
break;
case Status.idle:
print("waiting");
break;
case Status.maintenance:
print("under maintenance");
break;
}
}
Test yourself
-
Match switch parts
- switch
- starts branching
- case
- catches a constant
- break
- exits the branch
- default
- for unmatched cases
-
What is required when using switch with enum?
switch (s) {
case Status.active: ...
}
- The constant name is written directly
- if is also written
- default is required
- break after the case
Show answer
if is also written — break after a case is needed to exit.
-
The case label
switch (s) {
____: print("running"); break;
}
Show answer
switch (s) {
case Status.active: print("running"); break;
}
Next lesson: Enum and patterns