Enhanced Enums
An enum (enumerated type) is a fixed set of named values: the days of the week, order statuses, log levels. Dart enums are much more than named integers — since Dart 2.17 they can have fields, constructors, methods and even implement interfaces. These are called enhanced enums.
Simple enums
enum OrderStatus { pending, paid, shipped, delivered, cancelled }
void main() {
var status = OrderStatus.paid;
print(status);
print(status.name);
print(status.index);
print(OrderStatus.values);
print(OrderStatus.values.byName('shipped'));
print(status == OrderStatus.paid);
}OrderStatus.paid
paid
1
[OrderStatus.pending, OrderStatus.paid, OrderStatus.shipped, OrderStatus.delivered, OrderStatus.cancelled]
OrderStatus.shipped
true
| Member | Meaning |
|---|---|
.name |
The value's identifier as a String |
.index |
Zero-based position in the declaration |
Enum.values |
A List of all values, in order |
values.byName('x') |
Look up a value from its name (throws if missing) |
values.asNameMap() |
A Map<String, Enum> for safe lookups |
Exhaustive switches
The compiler knows every value of an enum, so a switch must cover them all (or use _). Add a new status later and the compiler points to every switch you need to update:
enum OrderStatus { pending, paid, shipped, delivered, cancelled }
String icon(OrderStatus s) => switch (s) {
OrderStatus.pending => '⏳',
OrderStatus.paid => '💳',
OrderStatus.shipped => '🚚',
OrderStatus.delivered => '📦',
OrderStatus.cancelled => '✖',
};
void main() {
for (final s in OrderStatus.values) {
print('${icon(s)} ${s.name}');
}
}⏳ pending
💳 paid
🚚 shipped
📦 delivered
✖ cancelled
Enhanced enums: fields, constructors, methods
Enum values can carry data. Declare final fields and a const constructor, then pass arguments to each value:
enum Planet {
mercury(mass: 3.303e+23, radius: 2.4397e6),
earth(mass: 5.976e+24, radius: 6.37814e6),
jupiter(mass: 1.9e+27, radius: 7.1492e7);
const Planet({required this.mass, required this.radius});
final double mass; // kg
final double radius; // m
static const double g = 6.67300e-11;
double get surfaceGravity => g * mass / (radius * radius);
bool get isGiant => radius > 2e7;
}
void main() {
for (final p in Planet.values) {
final gravity = p.surfaceGravity.toStringAsFixed(2);
print('${p.name.padRight(8)} g=$gravity m/s²${p.isGiant ? ' (giant)' : ''}');
}
}mercury g=3.70 m/s²
earth g=9.80 m/s²
jupiter g=24.81 m/s² (giant)
Rules for enhanced enums:
- Values are listed first, separated by commas, and the list ends with
;when other members follow. - All instance fields must be
final, and the generative constructor must beconst. - Enums can't be extended, and you can't create new instances — the values are the only instances.
factoryconstructors are allowed, but they must return one of the existing values.
Enums with interfaces and mixins
An enum can implements interfaces and use mixins, so it fits into polymorphic code:
abstract interface class Priced {
int get priceCents;
}
enum Size implements Priced, Comparable<Size> {
small(label: 'S', priceCents: 3000),
medium(label: 'M', priceCents: 3500),
large(label: 'L', priceCents: 4200);
const Size({required this.label, required this.priceCents});
final String label;
@override
final int priceCents;
factory Size.fromLabel(String label) =>
values.firstWhere((s) => s.label == label.toUpperCase(), orElse: () => medium);
@override
int compareTo(Size other) => index - other.index;
Size? get next => index + 1 < values.length ? values[index + 1] : null;
}
void main() {
final s = Size.fromLabel('s');
print('${s.name}: ${s.priceCents / 100} USD');
print(s.next);
print(Size.large.next);
print(Size.fromLabel('XL'));
final List<Priced> items = [Size.large, Size.small];
print(items.fold<int>(0, (sum, i) => sum + i.priceCents));
print(Size.large.compareTo(Size.small) > 0);
}small: 30.0 USD
Size.medium
null
Size.medium
7200
true
Parsing enums safely
byName throws for unknown input. For user or JSON data, use asNameMap() and a fallback:
final status = OrderStatus.values.asNameMap()[json['status']] ?? OrderStatus.pending;Tip: Store enums in databases or JSON by
name, not byindex— reordering the declaration would silently change every stored index.
Test yourself
What does OrderStatus.paid.name return?
- 'OrderStatus.paid'
- 'paid'
- 1
- 'PAID'
Which is required for an enhanced enum with fields?
- A factory constructor
- A const constructor and final fields
- A static values list you write yourself
- Extending the Enum class
Why is storing an enum's index in a database risky?
- Indexes are random
- Reordering or inserting values changes the indexes
- Indexes are strings
- Enums don't have indexes