Extension Methods & Types
Sometimes you wish String had an isEmail getter or int had a minutes property. You can't edit dart:core, and subclassing String isn't allowed. Extension methods let you add methods, getters, setters and operators to any existing type — including ones you don't own — without changing or wrapping it.
Declaring an extension
extension StringTools on String {
bool get isBlank => trim().isEmpty;
String capitalize() =>
isEmpty ? this : '${this[0].toUpperCase()}${substring(1).toLowerCase()}';
String truncate(int max, {String ellipsis = '…'}) =>
length <= max ? this : '${substring(0, max)}$ellipsis';
}
void main() {
print(' '.isBlank);
print('hELLO wORLD'.capitalize());
print('A very long product title'.truncate(10));
print('short'.truncate(10));
}true
Hello world
A very lon…
short
Inside the extension, this (often implicit) is the receiver — the string the method was called on.
Extensions on numbers, collections and generics
Extensions can target any type, including generic ones:
extension DurationShortcuts on int {
Duration get minutes => Duration(minutes: this);
Duration get seconds => Duration(seconds: this);
}
extension Stats on Iterable<num> {
num get sum => fold(0, (a, b) => a + b);
double get average => isEmpty ? 0 : sum / length;
}
extension ListSafety<T> on List<T> {
T? at(int index) => index >= 0 && index < length ? this[index] : null;
}
void main() {
final timeout = 2.minutes + 30.seconds;
print(timeout.inSeconds);
print([4, 8, 15, 16, 23, 42].average);
print(<int>[].sum);
final names = ['Ky', 'Lam'];
print(names.at(1));
print(names.at(5));
}150
18.0
0
Lam
null
ListSafety<T> is a generic extension: T is inferred from the list it's called on, so names.at(1) returns a String?.
Extensions on nullable types
An extension on String? can be called on a value that might be null — no ?. needed:
extension NullableText on String? {
bool get isNullOrEmpty => this == null || this!.isEmpty;
String orDash() => isNullOrEmpty ? '-' : this!;
}
void main() {
String? phone;
String? email = 'hi@site.vn';
print(phone.isNullOrEmpty);
print(phone.orDash());
print(email.orDash());
}true
-
hi@site.vn
Static resolution and conflicts
Extensions are resolved statically — based on the variable's declared type, not the runtime type. So they don't work on dynamic:
extension Shout on String {
String shout() => '${toUpperCase()}!';
}
void main() {
String a = 'hey';
print(a.shout());
dynamic b = 'hey';
try {
print(b.shout());
} on NoSuchMethodError {
print('dynamic receiver: extension not found');
}
// Explicit application, useful when two extensions clash
print(Shout('ok').shout());
}HEY!
dynamic receiver: extension not found
OK!
If two imported extensions define the same member for the same type, the call is ambiguous. Resolve it by calling one explicitly (Shout(a).shout()) or by hiding one at import: import 'lib.dart' hide OtherShout;.
| Rule | Detail |
|---|---|
| Members allowed | Methods, getters, setters, operators, static members |
| Not allowed | Instance fields, constructors |
| Overrides real members? | No — a real class member always wins |
Unnamed extension on X |
Allowed, but only usable in its own file |
Extension types (Dart 3.3)
An extension type wraps an existing type in a new, compile-time-only type with its own API. It has zero runtime cost: at runtime the value is just the underlying representation. It's perfect for giving meaning to primitive values, like IDs that shouldn't be mixed up:
extension type UserId(int value) {
bool get isSystem => value < 100;
}
extension type OrderId(int value) {}
String loadUser(UserId id) => 'user ${id.value}${id.isSystem ? ' (system)' : ''}';
void main() {
final u = UserId(42);
final o = OrderId(42);
print(loadUser(u));
// loadUser(o); // compile error: OrderId is not a UserId
// loadUser(42); // compile error: int is not a UserId
print(o.value);
}user 42 (system)
42
| Extension method | Extension type | |
|---|---|---|
| Creates a new type? | No | Yes (static only) |
| Adds members to | All values of the type | Only values typed as the extension type |
| Typical use | Convenience helpers | Type-safe wrappers (UserId, Cents) with no allocation |
Tip: Don't overdo extensions. Put them in a clearly named file (
string_extensions.dart) so readers can find wherecapitalize()comes from.
Test yourself
Can an extension add an instance field to String?
- Yes
- No — extensions can add methods, getters, setters and operators, but not instance fields
- Only final fields
- Only in Dart 3
Why doesn't an extension method work on a dynamic variable?
- Extensions are resolved using the static type
- dynamic values are always null
- Extensions only work on classes you own
- It does work
What is the runtime cost of an extension type like extension type UserId(int value)?
- A wrapper object per value
- None — at runtime it's just the int
- A map lookup
- It boxes the value