Enum and patterns
- Dart course
- Beginner
- Lesson 98/116
- 5 min
Learn enums with pattern matching.
Pattern matching
Dart 3's pattern matching is very powerful with enums. switch can now be written as an expression that returns a value; no break needed. Each case matches a pattern and produces a value. The result can be assigned directly to a variable.
Example: final label = switch (s) { Status.active => "running", Status.idle => "waiting", Status.maintenance => "under maintenance" };. The expression to the right of the arrow (=>) is the case's result. Cases are separated by commas, no break. When all constants are covered, default is not needed; this produces short, safe code.
Practice Your turn: switch expression
Define an enum Approval with pending, approve, reject. In main assign final a = Approval.approve; and use a switch expression to return "approved" for Approval.approve. Print the result. Cover all constants.
Starter code
void main() {
// Define Approval enum: pending, approve, reject
// Use a switch expression to produce a label and print
}Sample solution
enum Approval { pending, approve, reject }
void main() {
final a = Approval.approve;
final label = switch (a) {
Approval.pending => "pending",
Approval.approve => "approved",
Approval.reject => "rejected",
};
print(label);
}Expected output
approved
Destructuring
Pattern matching does not just catch the enum constant; it can also destructure fields of an enhanced enum. Inside a case you write the constant name and the field names in parentheses to access them directly. Like case Heat high(: final degrees):. This is especially powerful with multi-field enhanced enums.
Moreover, the underscore _ catches the "all other cases" pattern; _ => "unknown". This is like default but shorter. Still, with _ the compiler will not warn when a new constant is added, so writing all constants out is usually safer. Pattern matching, switch expressions and enhanced enums form a strong Dart 3 trio.
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 The switch expression arrow
final label = switch (s) { Status.active ____ "running", Status.idle => "waiting" };
final label = switch (s) { Status.active => "running", Status.idle => "waiting" };
Explanation: => binds the pattern on the left to the value on the right.
2 When is a switch expression more useful?
final s = switch (x) { A => 1, B => 2 };- default is required
- break is required
- Each case returns a value Correct answer
- it cannot replace if
Explanation: A switch expression returns a value; no break needed.
3 Match pattern
| Term | Meaning |
|---|---|
pattern |
shape to match |
=> |
produces a value |
_ |
all other cases |
destructure |
opens fields |