switch with enum
- Dart course
- Beginner
- Lesson 97/116
- 5 min
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.
Practice 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.
Starter code
void main() {
// Define Status enum: active, idle, maintenance
// final s = Status.maintenance;
// switch with a message for each case
}Sample 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;
}
}Expected output
under maintenance
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match switch parts
| Term | Meaning |
|---|---|
switch |
starts branching |
case |
catches a constant |
break |
exits the branch |
default |
for unmatched cases |
2 What is required when using switch with enum?
switch (s) {
case Status.active: ...
}- The constant name is written directly
- if is also written Correct answer
- default is required
- break after the case
Explanation: break after a case is needed to exit.
3 The case label
switch (s) {
____: print("running"); break;
}
switch (s) {
case Status.active: print("running"); break;
}
Explanation: The constant name comes after case.