Dart
Summary - Enums
Combine enum and enhanced enum to write a state machine.
Summary - Enums
In this group we introduced enums: classic enum definition, .values and .index access, Dart 3 enhanced enum with fields and methods, branching with switch and pattern matching. Now we combine them all in a state machine.
A state machine is a system that has defined states and transitions. For example an order: from pending to preparing, then to shipped. An enhanced enum carries data per state; a switch expression turns a state into a label. This shows how to use enums in a real application.
Exercise Your turn: produce a state label
Define an enum Order with pending, preparing, shipped, delivered. In main assign final o = Order.preparing; and use a switch expression to produce a label for each state: "pending", "preparing", "shipped", "delivered". Print the result.
Show example solution
enum Order { pending, preparing, shipped, delivered }
void main() {
final o = Order.preparing;
final label = switch (o) {
Order.pending => "pending",
Order.preparing => "preparing",
Order.shipped => "shipped",
Order.delivered => "delivered",
};
print(label);
}
Exercise Your turn: state with enhanced enum
Define an enhanced enum Stage with start(0), middle(50), end(100). Add final int percent and a const Stage(this.percent) constructor. In main assign final s = Stage.middle; and use a switch expression to produce a string like "%50" using percent; same shape for all constants. Print the result.
Show example solution
enum Stage { start(0), middle(50), end(100); final int percent; const Stage(this.percent); }
void main() {
final s = Stage.middle;
final label = switch (s) {
Stage.start => "%${s.percent}",
Stage.middle => "%${s.percent}",
Stage.end => "%${s.percent}",
};
print(label);
}
Test yourself
-
Match the state machine
- enum
- defines the states
- switch expression
- produces a label
- enhanced enum
- carries state data
- pattern matching
- destructures fields
-
Which defines the states in a state machine?
enum Order { pending, preparing, shipped }
Show answer
switch — enum carries the state names.
Next lesson: try/catch