Sub topic 10
Enums and extension methods
This chapter assumes you know Dart classes, constructors, final fields, and switch expressions from the earlier chapters. It covers how enums work in Dart 3, how to give them fields and behavior, and how extension methods add members to types you don't own.
Simple enums
An enum is a type with a fixed set of named values. Each value is a constant instance of the enum.
enum Direction { north, east, south, west }
void main() {
print(Direction.east.name);
print(Direction.east.index);
print(Direction.values);
}This prints east, 1, and [Direction.north, Direction.east, Direction.south, Direction.west].
nameis the identifier as a string.indexis the zero-based declaration position.valuesis a constant list of all instances in declaration order.
Because an enum has a closed set of values, the compiler can check that a switch covers all of them:
enum Direction { north, east, south, west }
String arrow(Direction d) => switch (d) {
Direction.north => 'up',
Direction.east => 'right',
Direction.south => 'down',
Direction.west => 'left',
};
void main() => print(arrow(Direction.south));A switch expression over an enum must be exhaustive. If you add Direction.up later, every switch without a default case fails to compile. This is the main reason to prefer enums over strings or integers.
Enhanced enums
Since Dart 2.17, an enum can have fields, constructors, methods, getters, and static members, just like a class.
enum Status implements Comparable<Status> {
pending(code: 0, label: 'Pending'),
active(code: 1, label: 'Active'),
closed(code: 2, label: 'Closed');
const Status({required this.code, required this.label});
final int code;
final String label;
bool get isOpen => this != closed;
static Status fromCode(int code) =>
values.firstWhere((s) => s.code == code);
@override
int compareTo(Status other) => code.compareTo(other.code);
}
void main() {
print(Status.fromCode(1).label);
print(Status.pending.compareTo(Status.closed));
print(Status.closed.isOpen);
}This prints Active, -1, and false.
The rules for enhanced enums:
- Every instance field must be
final. - Constructors must be
const. - The value list ends with a semicolon when members follow it.
- An enum can
implementinterfaces and usewithmixins. - An enum cannot
extenda class, be subclassed, or be instantiated withnew. - An enum cannot override
index,hashCode, or==.
Static methods such as fromCode live inside the enum's scope, so values needs no prefix there.
Looking up values by name
Converting a string such as JSON input into an enum is a common task. The standard library provides helpers on values:
enum Direction { north, east, south, west }
void main() {
print(Direction.values.byName('west'));
final lookup = Direction.values.asNameMap();
print(lookup['up']);
print(lookup['north']);
}byName throws an ArgumentError for an unknown name. asNameMap() returns a Map<String, Direction>, so a missing key gives null. Use byName when bad input is a bug, and asNameMap()[...] when you want to handle bad input yourself.
Extension methods
An extension adds members to an existing type without editing or subclassing it. You can extend your own types, core types such as String, and enums.
extension StringCase on String {
String get capitalized =>
isEmpty ? this : '${this[0].toUpperCase()}${substring(1)}';
bool get isBlank => trim().isEmpty;
}
void main() {
print('dart'.capitalized);
print(' '.isBlank);
}Inside the extension body, this is the receiver, and you can call its members directly, as isEmpty and substring are above. Extensions can declare methods, getters, setters, operators, and static members. They cannot declare instance fields or constructors.
Extending an enum
Extensions are a good way to add behavior to an enum without crowding its declaration, for example when the enum is generated or shared:
enum Direction { north, east, south, west }
extension DirectionX on Direction {
Direction get opposite =>
Direction.values[(index + 2) % Direction.values.length];
}
void main() => print(Direction.north.opposite);This prints Direction.south. The opposite getter relies on declaration order, so it is only correct as long as the values stay in clockwise order. Put a comment next to the enum to say so.
Generic and nullable receivers
An extension can have type parameters, and its receiver type can be nullable.
extension Chunking<T> on List<T> {
List<List<T>> chunked(int size) => [
for (var i = 0; i < length; i += size)
sublist(i, i + size > length ? length : i + size),
];
}
extension NullableString on String? {
bool get isNullOrEmpty => this?.isEmpty ?? true;
}
void main() {
print([1, 2, 3, 4, 5].chunked(2));
String? name;
print(name.isNullOrEmpty);
}This prints [[1, 2], [3, 4], [5]] and true. Calling name.isNullOrEmpty on a null value works because extensions are resolved by the static type, not by an object lookup. An ordinary method call on null would throw.
How extensions are resolved
Extension members are resolved at compile time from the static type of the receiver. This has three consequences.
- An instance member of the type always wins over an extension member with the same name.
- If the static type is
dynamic, extensions are not applied. - An extension is only visible where it is imported or declared.
extension StringCase on String {
String get capitalized =>
isEmpty ? this : '${this[0].toUpperCase()}${substring(1)}';
}
void main() {
dynamic d = 'hello';
try {
print(d.capitalized);
} on NoSuchMethodError {
print('not found at runtime');
}
String s = d;
print(s.capitalized);
}The first call fails at runtime because d is dynamic. After assigning to a String variable, the call resolves.
Resolving conflicts
When two imported extensions define the same member on the same type and neither is more specific, the call is ambiguous. You have three options:
// Hide one extension at import time.
import 'text_utils.dart' hide StringCase;
// Or apply an extension explicitly by name.
void main() {
print(StringCase('dart').capitalized);
}You can also use show to import only the names you want. Explicit application, such as StringCase('dart'), is also how you call an extension member that an instance member would otherwise shadow.
Unnamed extensions
An extension without a name is private to its library:
extension on String {
String get twice => '$this$this';
}This is useful for helpers you don't want to export. You cannot apply an unnamed extension explicitly or hide it, so use it only when no conflict is possible.
Choosing between a member and an extension
| Need | Use |
|---|---|
| Data that belongs to each enum value | A field on the enhanced enum |
| Logic that is core to the type and you own it | A method inside the enum or class |
| Helpers for a type you don't own (`String`, `List`) | An extension |
| Optional, feature-specific behavior | An extension in its own file |
| Behavior that must be overridden polymorphically | A class method, not an extension |
Extensions are not polymorphic. They never override anything, and a subclass cannot override one. They are static helpers with method syntax.
Common errors
- Switch not exhaustive. You added an enum value and used a switch expression without a default. Add the missing case.
ArgumentErrorfrombyName. The input string is not a value name. UseasNameMap()[key]and handlenull.- "Non-final field in an enum." Enum fields must be
final. - Extension method "isn't defined". The extension is not imported, or the receiver's static type is
dynamicor a supertype such asObject. - Ambiguous extension access. Two imports define the same member. Hide one or apply one explicitly.
Exercise
Write an enhanced enum Size with values small, medium, and large, each holding an int ml (250, 350, 500). Then write an extension on Size with a getter bigger that returns the next larger size, or the same size if it is already large. What does Size.medium.bigger.ml print?
Show answer
enum Size { small(250), medium(350), large(500); const Size(this.ml); final int ml; } extension SizeX on Size { Size get bigger => Size.values[(index + 1).clamp(0, Size.values.length - 1)]; } Size.medium.bigger is Size.large, so the expression prints 500.
Exercise
A function has the static type Object and receives the string 'dart'. Calling value.capitalized fails to compile, even though StringCase on String is imported. Why, and how do you fix it?
Show answer
Extension members are resolved from the static type, and Object is not String, so StringCase does not apply. Fix it by checking or casting to the right type first, for example if (value is String) print(value.capitalized);, which promotes value to String.