Summary - Enums
- Dart course
- Beginner
- Lesson 99/116
- 5 min
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.
Practice 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.
Starter code
void main() {
// Define Order enum: pending, preparing, shipped, delivered
// Use a switch expression to produce a label and print
}Sample 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);
}Expected output
preparing
Practice 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.
Starter code
void main() {
// Define Stage enhanced enum: start(0), middle(50), end(100)
// Use a switch expression to produce "%<percent>" and print
}Sample 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);
}Expected output
%50
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the state machine
| Term | Meaning |
|---|---|
enum |
defines the states |
switch expression |
produces a label |
enhanced enum |
carries state data |
pattern matching |
destructures fields |
2 Which defines the states in a state machine?
enum Order { pending, preparing, shipped }- enum
- for
- if
- switch Correct answer
Explanation: enum carries the state names.