Dart
Enum and patterns
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.
Exercise 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.
Show example 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);
}
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.
Test yourself
-
The switch expression arrow
final label = switch (s) { Status.active ____ "running", Status.idle => "waiting" };
Show answer
final label = switch (s) { Status.active => "running", Status.idle => "waiting" };
-
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
- it cannot replace if
Show answer
Each case returns a value — A switch expression returns a value; no break needed.
-
Match pattern
- pattern
- shape to match
- =>
- produces a value
- _
- all other cases
- destructure
- opens fields
Next lesson: Summary - Enums