Enhanced enums
suggest changeSince Dart 2.17, an enum is a full class with a fixed set of instances. Besides a list of names, it can have:
finalfields andconstconstructors, including named and factory constructors- methods, getters, operators and static members
- interfaces it implements and mixins it uses
- type parameters
Dart 3.0 added exhaustiveness checking, so a switch over an enum needs no default and the compiler tells you every place to update when you add a value. Dart 3.10 added dot shorthands, which let you write .red instead of Color.red when the type is known.
This article covers all of these. Every example was run with Dart 3.13. For the basic syntax, see Basic usage.
Built-in members of every enum
Even the simplest enum gets useful members for free:
enum Weekday { monday, tuesday, wednesday, thursday, friday, saturday, sunday }
void main() {
print(Weekday.friday);
print(Weekday.friday.name);
print(Weekday.friday.index);
print(Weekday.values.length);
print(Weekday.values.first);
print(Weekday.values.byName('sunday'));
print(Weekday.values.asNameMap()['sunday']);
print(Weekday.values.asNameMap()['funday']);
final days = [Weekday.sunday, Weekday.monday, Weekday.friday];
days.sort(Enum.compareByIndex);
print(days);
print(Weekday.monday == Weekday.values[0]);
print(identical(Weekday.monday, Weekday.values.byName('monday')));
print(Weekday.monday is Enum);
}
Output:
Weekday.friday
friday
4
7
Weekday.monday
Weekday.sunday
Weekday.sunday
null
[Weekday.monday, Weekday.friday, Weekday.sunday]
true
true
true
| Member | What it gives you |
|---|---|
values |
a const List of all values, in declaration order |
name |
the identifier as a String: 'friday' |
index |
the zero-based position in values |
values.byName(s) |
the value named s, or an ArgumentError |
values.asNameMap() |
a Map<String, E> from name to value |
Enum.compareByIndex |
a comparator that sorts by declaration order |
Enum.compareByName |
a comparator that sorts by name |
Every enum value is a compile-time constant and a singleton, so == is identity. Every enum type implements Enum, which is how generic code like Enum.compareByIndex works on any enum.
byName is case-sensitive and throws on unknown names:
enum Weekday { monday, tuesday, wednesday, thursday, friday, saturday, sunday }
void main() {
try {
Weekday.values.byName('Monday');
} on ArgumentError catch (e) {
print(e);
}
final lower = {for (final d in Weekday.values) d.name.toLowerCase(): d};
print(lower['MONDAY'.toLowerCase()]);
print(Weekday.values.asNameMap().runtimeType);
print(Weekday.values.indexed.where((e) => e.$1 >= 5).map((e) => e.$2).toList());
print(Weekday.values.sublist(Weekday.monday.index, Weekday.friday.index + 1));
final names = [Weekday.sunday, Weekday.friday, Weekday.monday]
..sort(Enum.compareByName);
print(names);
}
Output:
Invalid argument (name): No enum value with that name: "Monday"
Weekday.monday
_Map<String, Weekday>
[Weekday.saturday, Weekday.sunday]
[Weekday.monday, Weekday.tuesday, Weekday.wednesday, Weekday.thursday, Weekday.friday]
[Weekday.friday, Weekday.monday, Weekday.sunday]
asNameMap() builds a new map on every call. If you look up names often, store the map in a variable (or a static final field, shown later) instead of calling it each time.
Fields, constructors and methods
An enhanced enum lists its values first, each with constructor arguments, followed by a semicolon and then ordinary class members:
enum HttpStatus {
ok(200, 'OK'),
created(201, 'Created'),
noContent(204, 'No Content'),
notFound(404, 'Not Found'),
tooManyRequests(429, 'Too Many Requests'),
internalServerError(500, 'Internal Server Error');
const HttpStatus(this.code, this.reason);
final int code;
final String reason;
bool get isSuccess => code >= 200 && code < 300;
bool get isClientError => code >= 400 && code < 500;
bool get isRetryable => this == tooManyRequests || code >= 500;
String get statusLine => 'HTTP/1.1 $code $reason';
static HttpStatus? fromCode(int code) {
for (final s in values) {
if (s.code == code) return s;
}
return null;
}
@override
String toString() => '$code $reason';
}
void main() {
const s = HttpStatus.notFound;
print(s);
print(s.name);
print(s.statusLine);
print('${s.isClientError} ${s.isRetryable}');
print(HttpStatus.fromCode(429)?.isRetryable);
print(HttpStatus.fromCode(418));
print(HttpStatus.values.where((s) => s.isSuccess).toList());
}
Output:
404 Not Found
notFound
HTTP/1.1 404 Not Found
true false
true
null
[200 OK, 201 Created, 204 No Content]
Inside the enum body you can refer to other values without the type name (this == tooManyRequests) and to values directly. Overriding toString is allowed and changes how the values print.
Data that belongs to each value now lives in one place. Without enhanced enums you would keep it in separate maps or switch statements, and adding a value would mean finding and updating each of them.
Named and factory constructors
An enum can have several generative constructors, as long as all of them are const. A value picks one by name. Factory constructors can't create new values, but they can return an existing one, which makes them a natural place for parsing:
enum Color {
red.rgb(0xFF0000),
green.rgb(0x00FF00),
blue.rgb(0x0000FF),
black.gray(0),
white.gray(255);
const Color.rgb(this.value);
const Color.gray(int level) : value = level << 16 | level << 8 | level;
final int value;
factory Color.parse(String hex) {
final v = int.parse(hex.replaceFirst('#', ''), radix: 16);
return values.firstWhere(
(c) => c.value == v,
orElse: () => throw ArgumentError.value(hex, 'hex', 'not a named color'),
);
}
String get hex => '#${value.toRadixString(16).padLeft(6, '0')}';
}
void main() {
print(Color.white.hex);
print(Color.parse('#00ff00'));
try {
Color.parse('#123456');
} on ArgumentError catch (e) {
print(e);
}
}
Output:
#ffffff
Color.green
Invalid argument (hex): not a named color: "#123456"
Primary constructors
Dart 3.13 added primary constructors, which work on enums too. They declare the fields and the constructor in the header:
enum Planet(final double mass, final double radius) {
mercury(3.303e+23, 2.4397e6),
earth(5.976e+24, 6.37814e6);
double get surfaceGravity => 6.67300E-11 * mass / (radius * radius);
}
void main() {
for (final p in Planet.values) {
print('${p.name}: ${p.surfaceGravity.toStringAsFixed(2)} m/s²');
}
}
Output:
mercury: 3.70 m/s²
earth: 9.80 m/s²
With language version 3.13, const is also implied on enum constructors, so Planet(this.mass, this.radius); compiles without it. Code that must support older SDKs (with sdk: ^3.12.0 or lower in pubspec.yaml) still needs const, or it fails with Generative enum constructors must be 'const'.
Rules and restrictions
An enum is still a closed set of constants, so the compiler enforces a few rules. This file breaks most of them:
enum Level {
low(1),
high(10);
Level(this.weight);
int weight;
int get values => 0;
@override
bool operator ==(Object other) => false;
}
class Extra extends Level {}
void main() {
final l = Level(5);
}
$ dart analyze bad.dart
error - bad.dart:6:7 - Enums can only declare final fields. Try making the field final. - non_final_field_in_enum
error - bad.dart:8:11 - A member named 'values' can't be declared in an enum. Try using a different name. - values_declaration_in_enum
error - bad.dart:11:17 - A concrete instance member named '==' can't be declared in a class that implements 'Enum'. Try using a different name. - illegal_concrete_enum_member
error - bad.dart:14:21 - Classes can only extend other classes. Try specifying a different superclass, or removing the extends clause. - extends_non_class
error - bad.dart:17:13 - Generative enum constructors can only be used to create an enum constant. Try using an enum value, or a factory constructor. - invalid_reference_to_generative_enum_constructor
In short:
- All instance fields are
final, and every value is a deeply constant object. Enums are immutable (see Immutability). Mutable state attached to a value belongs in a separate map keyed by the enum. - You can't declare
values,index,hashCodeor==. Equality is always identity. - Nothing can extend an enum, and enums can't extend classes. They can implement interfaces and use mixins.
- Generative constructors run only in the value list. Factory constructors can be called anywhere but must return an existing value.
- Every member needs a body. Unlike Java, a value can't have its own class body, so
int get sides;gives'sides' must have a method body because 'A' is an enum. Use aswitchonthisor a function-typed field instead (shown below).
Implementing interfaces and using mixins
Enums can implement any interface and use any mixin. A mixin declared on Enum can use index and name:
abstract interface class Labeled {
String get label;
}
mixin Describe on Enum implements Labeled {
String describe() => '#$index $name ($label)';
}
enum Priority with Describe implements Comparable<Priority> {
low('Low', 1),
normal('Normal', 5),
high('High', 10),
urgent('Urgent!', 100);
const Priority(this.label, this.weight);
@override
final String label;
final int weight;
@override
int compareTo(Priority other) => weight - other.weight;
bool operator <(Priority other) => compareTo(other) < 0;
bool operator >(Priority other) => compareTo(other) > 0;
}
String shout(Labeled l) => l.label.toUpperCase();
void main() {
print(Priority.high.describe());
print(shout(Priority.normal));
print(Priority.urgent > Priority.high);
final tasks = [Priority.normal, Priority.urgent, Priority.low];
tasks.sort();
print(tasks);
final highest = tasks.reduce((a, b) => a > b ? a : b);
print(highest.label);
}
Output:
#2 high (High)
NORMAL
true
[Priority.low, Priority.normal, Priority.urgent]
Urgent!
Because Priority implements Comparable, sort() needs no comparator and generic code bounded by T extends Comparable<T> accepts it. See Implicit interfaces and Sorting. You can't override ==, but you can define < and >.
Behavior per value
Java lets each enum constant override methods in its own body. Dart doesn't, and there are two ways to get the same effect.
A switch on this inside a getter or method keeps the logic in the enum. Inside the body, a bare value name like circle is a constant pattern:
enum Shape {
circle,
square,
triangle;
int get sides => switch (this) {
circle => 0,
square => 4,
triangle => 3,
};
}
When the behavior is a function, store it in a field. The tear-off of a top-level or static function is a constant, so it can be a constructor argument. Defining call makes the values callable. The main below uses both Op and the Shape enum above:
enum Op {
add('+', _add),
sub('-', _sub),
mul('*', _mul),
div('/', _div);
const Op(this.symbol, this._apply);
final String symbol;
final num Function(num, num) _apply;
num call(num a, num b) => _apply(a, b);
static Op? fromSymbol(String s) =>
values.where((op) => op.symbol == s).firstOrNull;
}
num _add(num a, num b) => a + b;
num _sub(num a, num b) => a - b;
num _mul(num a, num b) => a * b;
num _div(num a, num b) => a / b;
void main() {
for (final op in Op.values) {
print('6 ${op.symbol} 3 = ${op(6, 3)}');
}
print(Op.fromSymbol('*')?.call(7, 6));
print(Shape.values.map((s) => '${s.name}=${s.sides}').join(', '));
}
Output:
6 + 3 = 9
6 - 3 = 3
6 * 3 = 18
6 / 3 = 2.0
42
circle=0, square=4, triangle=3
Generic enums
An enum can have type parameters, and each value picks its own type argument. This gives you a typed set of keys, for example for settings:
enum Setting<T extends Object> {
volume<int>(50),
darkMode<bool>(false),
userName<String>('guest');
const Setting(this.defaultValue);
final T defaultValue;
T read(Map<String, Object?> prefs) {
final v = prefs[name];
return v is T ? v : defaultValue;
}
}
void main() {
final prefs = {'volume': 80, 'darkMode': 'yes'};
int vol = Setting.volume.read(prefs);
bool dark = Setting.darkMode.read(prefs);
String user = Setting.userName.read(prefs);
print('$vol $dark $user');
print(Setting.values.map((s) => s.defaultValue.runtimeType).toList());
}
Output:
80 false guest
[int, bool, String]
Setting.volume has the static type Setting<int>, so read returns an int and assigning it to a bool is a compile error. The stored 'yes' for darkMode has the wrong type, so the default is used.
Static members and aliases
Static fields and methods work as in any class. A static const can act as an alias for an existing value; it isn't added to values:
enum LogLevel {
debug,
info,
warning,
error;
static const defaultLevel = info;
bool allows(LogLevel other) => other.index >= index;
}
void main() {
const minimum = LogLevel.defaultLevel;
for (final level in LogLevel.values) {
print('${level.name.padRight(7)} logged: ${minimum.allows(level)}');
}
final counts = <LogLevel, int>{for (final l in LogLevel.values) l: 0};
counts[LogLevel.error] = counts[LogLevel.error]! + 1;
print(counts);
print(LogLevel.values.length);
}
Output:
debug logged: false
info logged: true
warning logged: true
error logged: true
{LogLevel.debug: 0, LogLevel.info: 0, LogLevel.warning: 0, LogLevel.error: 1}
4
Comparing index values, as allows does, is fine for ordering inside one program. Don't store index in files or databases, because reordering the values would silently change its meaning. Enum values make efficient map keys, and their indices make good bit positions for flag sets (see Bit manipulation). An enum with a single value is also a simple way to write a singleton.
Exhaustive switch
Since Dart 3.0, the compiler checks that a switch over an enum covers every value. With all values covered there's no need for default, and a function whose switch statement returns in every case doesn't need a return after it:
enum TrafficLight { red, yellow, green }
Duration wait(TrafficLight light) => switch (light) {
TrafficLight.red => const Duration(seconds: 30),
TrafficLight.yellow => const Duration(seconds: 3),
TrafficLight.green => Duration.zero,
};
TrafficLight next(TrafficLight light) {
switch (light) {
case TrafficLight.red:
return TrafficLight.green;
case TrafficLight.green:
return TrafficLight.yellow;
case TrafficLight.yellow:
return TrafficLight.red;
}
}
bool mayGo(TrafficLight light) => switch (light) {
.green => true,
.red || .yellow => false,
};
void main() {
var light = TrafficLight.red;
for (var i = 0; i < 4; i++) {
print('$light: wait ${wait(light).inSeconds}s, go: ${mayGo(light)}');
light = next(light);
}
}
Output:
TrafficLight.red: wait 30s, go: false
TrafficLight.green: wait 0s, go: true
TrafficLight.yellow: wait 3s, go: false
TrafficLight.red: wait 30s, go: false
The real benefit shows up when someone adds a value. Changing the declaration to enum TrafficLight { red, yellow, green, flashingYellow } turns all three switches into errors:
$ dart analyze
error - ex.dart:3:38 - The type 'TrafficLight' isn't exhaustively matched by the switch cases since it doesn't match the pattern 'TrafficLight.flashingYellow'. Try adding a wildcard pattern or cases that match 'TrafficLight.flashingYellow'. - non_exhaustive_switch_expression
error - ex.dart:10:3 - The type 'TrafficLight' isn't exhaustively matched by the switch cases since it doesn't match the pattern 'TrafficLight.flashingYellow'. Try adding a default case or cases that match 'TrafficLight.flashingYellow'. - non_exhaustive_switch_statement
error - ex.dart:20:35 - The type 'TrafficLight' isn't exhaustively matched by the switch cases since it doesn't match the pattern 'TrafficLight.flashingYellow'. Try adding a wildcard pattern or cases that match 'TrafficLight.flashingYellow'. - non_exhaustive_switch_expression
A default or _ case turns this check off: the code keeps compiling and the new value silently takes the default branch. Avoid wildcards on enums you own unless you really mean "everything else".
Patterns on enum fields
You can match on an enum's fields with object patterns. The compiler can't prove that conditions on fields cover every value, so such a switch needs a final _ case:
enum HttpStatus {
ok(200),
notFound(404),
tooManyRequests(429),
serviceUnavailable(503);
const HttpStatus(this.code);
final int code;
}
String advice(HttpStatus status) => switch (status) {
.tooManyRequests => 'slow down and retry',
HttpStatus(code: >= 500) => 'retry later',
HttpStatus(code: >= 400) => 'fix the request',
_ => 'done',
};
void log(String message, {HttpStatus status = .ok}) =>
print('[${status.code}] $message');
void main() {
for (final s in HttpStatus.values) {
print('${s.name}: ${advice(s)}');
}
log('fetched /users');
log('no such page', status: .notFound);
HttpStatus current = .serviceUnavailable;
if (current == .serviceUnavailable) print('backing off');
}
Output:
ok: done
notFound: fix the request
tooManyRequests: slow down and retry
serviceUnavailable: retry later
[200] fetched /users
[404] no such page
backing off
The .tooManyRequests, .ok and .notFound forms are dot shorthands (Dart 3.10). They work wherever the expected type is known: switch cases, arguments, default values, typed variables and the right side of ==. With var x = .ok; there's no type to look in, so it doesn't compile. More about matching in Switch case and Pattern matching.
Parsing enums from strings and JSON
APIs often spell values differently from Dart's lowerCamelCase names. Keep the wire value in a field and build a lookup map once, in a static final field (initialized lazily on first use):
import 'dart:convert';
enum OrderStatus {
pending('PENDING'),
paid('PAID'),
shipped('SHIPPED'),
cancelled('CANCELED');
const OrderStatus(this.wire);
/// The value used in the JSON API.
final String wire;
static final Map<String, OrderStatus> _byWire = {
for (final s in values) s.wire: s,
};
static OrderStatus? tryParse(String wire) => _byWire[wire];
static OrderStatus parse(String wire) =>
_byWire[wire] ??
(throw FormatException('Unknown order status', wire));
}
class Order {
final int id;
final OrderStatus status;
Order(this.id, this.status);
factory Order.fromJson(Map<String, Object?> json) => switch (json) {
{'id': int id, 'status': String s} => Order(id, OrderStatus.parse(s)),
_ => throw FormatException('Invalid order: $json'),
};
Map<String, Object?> toJson() => {'id': id, 'status': status.wire};
}
void main() {
final order = Order.fromJson(jsonDecode('{"id": 7, "status": "CANCELED"}'));
print(order.status);
print(jsonEncode(order));
print(OrderStatus.tryParse('REFUNDED'));
try {
Order.fromJson(jsonDecode('{"id": 8, "status": "REFUNDED"}'));
} on FormatException catch (e) {
print('${e.message}: ${e.source}');
}
}
Output:
OrderStatus.cancelled
{"id":7,"status":"CANCELED"}
null
Unknown order status: REFUNDED
Guidelines for parsing:
- Use
nameandvalues.byNamewhen you control both sides and the Dart names are the wire format. Use a field likewirewhen they differ, so renaming a Dart identifier can't break stored data. - Offer a
tryParsethat returnsnullnext to a throwingparse, likeint.parseandint.tryParse. - Throw a descriptive exception (
FormatExceptionfor bad input data) instead of lettingfirstWherethrow a bareStateError. - For data from a server that may add values later, consider an
unknownvalue andtryParse(s) ?? OrderStatus.unknown, so older clients keep working.
Object serialization shows how json_serializable does this with @JsonValue.
Enum or sealed class?
Both give you a closed set of cases and an exhaustive switch. The difference is where the data lives:
- With an enum, each case is a single constant object. All instances of
Currency.usdare the same object with the same fields. - With a sealed class, each case is a subclass, and each instance carries its own data, like a card number or an IBAN.
import 'dart:math';
// Every value has the same, fixed data: an enum.
enum Currency {
usd('\$', 2),
eur('€', 2),
jpy('¥', 0);
const Currency(this.symbol, this.decimals);
final String symbol;
final int decimals;
}
// Each case carries different data per instance: a sealed class.
sealed class Payment {
const Payment();
}
class Card extends Payment {
const Card(this.last4);
final String last4;
}
class BankTransfer extends Payment {
const BankTransfer(this.iban);
final String iban;
}
class Cash extends Payment {
const Cash();
}
String describe(Payment p, int amount, Currency c) {
// amount is in minor units: cents for USD, yen for JPY
final value = (amount / pow(10, c.decimals)).toStringAsFixed(c.decimals);
final how = switch (p) {
Card(:final last4) => 'card ending $last4',
BankTransfer(:final iban) => 'transfer from ${iban.substring(0, 4)}...',
Cash() => 'cash',
};
return '${c.symbol}$value by $how';
}
void main() {
print(describe(const Card('4242'), 1999, .usd));
print(describe(const BankTransfer('DE89370400440532013000'), 50000, .eur));
print(describe(const Cash(), 1200, .jpy));
}
Output:
$19.99 by card ending 4242
€500.00 by transfer from DE89...
¥1200 by cash
Choose an enum when the set of values is known at compile time and you want values, name, byName and cheap constant instances. Choose a sealed class when cases need different fields, new instances at runtime, or mutable state. See Inheritance for sealed classes and the other class modifiers.
Summary
- Put per-value data in
finalfields with aconstconstructor instead of parallel maps or switches. - Add getters and methods for behavior. Use
switch (this)or function-typed fields when each value behaves differently. - Implement
Comparableor other interfaces, and use mixinson Enumto share code between enums. - Switch over enums without
default, so adding a value shows every place that needs updating. - Parse with
byName,asNameMapor a cached lookup map, and never persistindex. - Use dot shorthands (
.notFound) when the type is obvious from context. - When cases need different data per instance, use a sealed class instead.