Dart Enums
An enum (enumerated type) defines a fixed set of named values — for example the days of the week, the status of an order or the screens of an app. Using an enum instead of strings or numbers means typos become compile errors, and switch statements can be checked for completeness.
Flutter uses enums everywhere: MainAxisAlignment.center, TextAlign.right, Brightness.dark, FontWeight.bold (that one is actually a class with constants, but it works the same way).
Declaring a simple enum
enum OrderStatus { pending, shipped, delivered, cancelled }
void main() {
var status = OrderStatus.shipped;
print(status);
print(status.name);
print(status.index);
print(status == OrderStatus.shipped);
print(OrderStatus.values);
}OrderStatus.shipped
shipped
1
true
[OrderStatus.pending, OrderStatus.shipped, OrderStatus.delivered, OrderStatus.cancelled]
| Member | Meaning |
|---|---|
.name |
The value's name as a String |
.index |
Its 0-based position in the declaration |
Enum.values |
A list of every value, in order |
Enum.values.byName('x') |
Look up a value from its name |
Enums and switch
A switch over an enum must cover every value (or include _). If you add a value later, the compiler shows you every switch that needs updating.
enum TrafficLight { red, yellow, green }
String action(TrafficLight light) => switch (light) {
TrafficLight.red => 'Stop',
TrafficLight.yellow => 'Slow down',
TrafficLight.green => 'Go',
};
void main() {
for (final light in TrafficLight.values) {
print('${light.name}: ${action(light)}');
}
}red: Stop
yellow: Slow down
green: Go
Try deleting the green case and running again — the code no longer compiles because the switch is not exhaustive.
Enhanced enums: fields, constructors and methods
Since Dart 2.17 enums can have final fields, a const constructor, getters and methods. This keeps related data next to the value instead of scattered in switch statements.
enum Planet {
mercury(diameterKm: 4879, hasRings: false),
earth(diameterKm: 12742, hasRings: false),
saturn(diameterKm: 116460, hasRings: true);
const Planet({required this.diameterKm, required this.hasRings});
final int diameterKm;
final bool hasRings;
bool get isGiant => diameterKm > 50000;
String describe() =>
'$name: $diameterKm km${hasRings ? ', ringed' : ''}${isGiant ? ', giant' : ''}';
}
void main() {
for (final p in Planet.values) {
print(p.describe());
}
print(Planet.values.where((p) => p.hasRings).map((p) => p.name).toList());
}mercury: 4879 km
earth: 12742 km
saturn: 116460 km, ringed, giant
[saturn]
Converting from strings
When data arrives as text (from JSON or storage), use values.byName. It throws if the name doesn't exist, so wrap it — or search with where/firstOrNull for a safe fallback.
enum Theme { light, dark, system }
Theme parseTheme(String? raw) {
for (final t in Theme.values) {
if (t.name == raw) return t;
}
return Theme.system;
}
void main() {
print(Theme.values.byName('dark'));
print(parseTheme('light'));
print(parseTheme('purple'));
print(parseTheme(null));
}Theme.dark
Theme.light
Theme.system
Theme.system
Enums implementing interfaces
Enhanced enums can implement interfaces and use mixins. Here every value can be compared by a priority:
enum Priority implements Comparable<Priority> {
low(1),
medium(5),
high(10);
const Priority(this.weight);
final int weight;
@override
int compareTo(Priority other) => weight.compareTo(other.weight);
}
void main() {
final tasks = [Priority.medium, Priority.high, Priority.low, Priority.medium];
tasks.sort();
print(tasks.map((p) => p.name).join(' < '));
print(Priority.high.compareTo(Priority.low) > 0);
}low < medium < medium < high
true
When to use an enum
- A value comes from a small, fixed set known at compile time → enum.
- The set changes at runtime (categories from a server) → use a class or a
StringID instead. - Each case needs different data shapes (e.g.
Success(items)vsFailure(message)) → use asealedclass (see Inheritance & Mixins).
Tip: In Flutter you'll often store the selected tab or filter as an enum in your
Stateand switch on it insidebuild.
Test yourself
Given enum Size { s, m, l }, what is Size.l.index?
- 1
- 2
- 3
- 'l'
How do you get the text 'm' from Size.m?
- Size.m.toString()
- Size.m.name
- Size.m.value
- Size.m.text
What happens if a switch expression over an enum misses a value and has no _ case?
- It returns null
- It throws at runtime only
- It's a compile error
- The first case is used