Extension types
suggest changeAn extension type (Dart 3.3+) gives an existing value a new static type and a new set of members, without creating a wrapper object. It's declared with a header that names a single representation value:
extension type UserId(int value) {
bool get isAdmin => value < 100;
}
void main() {
final id = UserId(42);
print(id.value);
print(id.isAdmin);
// print(id + 1); // error: The operator '+' isn't defined for the type 'UserId'
int raw = id.value; // explicit unwrap
// int bad = id; // error: A value of type 'UserId' can't be assigned to 'int'
print(raw);
}
Output:
42
true
42
The compiler treats UserId as a separate type: an int isn't a UserId, a UserId isn't an int, and int members such as + aren't available unless you ask for them. At run time the extension type is gone. A UserId is the int 42, with no allocation and no extra indirection.
This article covers:
- the representation type, constructors and validation
- the members an extension type can and can't declare
implements: forwarding the representation's interface, or another extension type's- redeclaring members with
@redeclare, and why that isn't overriding - zero-cost units and typed views over JSON maps
- erasure pitfalls:
is,as, generics,switchanddynamic - choosing between extension types, classes, extension methods and typedefs
Several other articles use extension types for one specific job. This one explains the feature as a whole and links to them:
- "newtype" IDs next to records: Structs, tuples, and records
- forwarding a whole interface for free: Composition and delegation
- typed accessors over nested data: Nested classes
- wrapping JavaScript objects: JavaScript interop with dart:js_interop
The examples were run with Dart 3.13.4. Extension types need sdk: ^3.3.0 or later in pubspec.yaml.
The representation type and constructors
The parenthesized part of the header, (int value), declares two things:
- the representation type,
int, which is what the value really is at run time - a final representation field,
value, plus a constructor that sets it
The representation field is an ordinary getter. If you name it with a leading underscore, as in extension type Email._(String _s), code outside the library can't unwrap it. Making the constructor private, by naming it Name._, is the usual way to force all callers through a validating factory:
extension type Percent._(double value) {
// validating factory: the only public way to create a Percent
factory Percent(double v) {
if (v < 0 || v > 100) throw RangeError.range(v, 0, 100, 'v');
return Percent._(v);
}
// named factory that reuses the validation
factory Percent.fraction(double f) => Percent(f * 100);
// named generative constructor: must redirect to another generative one
Percent.unchecked(double v) : this._(v);
static final Percent zero = Percent._(0);
double get asFraction => value / 100;
Percent operator +(Percent other) => Percent(value + other.value);
String format() => '$value%';
}
void main() {
final a = Percent(40);
final b = Percent.fraction(0.25);
print((a + b).value);
print(b.asFraction);
print(Percent.zero.value);
print(Percent.unchecked(250).value);
print(a.format());
print(a); // it's a double at run time
try {
Percent(140);
} on RangeError catch (e) {
print(e);
}
}
Output:
65.0
0.25
0.0
250.0
40.0%
40.0
RangeError (v): Invalid value: Not in inclusive range 0..100: 140.0
Points to note:
- Factories, named generative constructors, static fields and static methods all work as in classes.
Percent.uncheckedshows the gap you leave if you add a generative constructor: it skips the factory's check. Only add one when that's intended.print(a)prints40.0, not40.0%.printcallstoString()at run time, and at run timeais adouble.extension type const UserId(int value)makes the representation constructorconst, so you can writeconst UserId(7).
Since Dart 3.13 the header follows the primary constructor rules: other constructors can be written as new name(...) and factory name(...), and final is allowed on the representation parameter.
Members you can and can't declare
An extension type can declare methods, getters, setters, operators and static members. It can't declare instance fields, because there is no object to hold them; all state lives in the representation:
extension type Meters(double value) {
int count = 0;
}
bin/e3.dart:2:7: Error: Extension types can't declare instance fields
Try removing the field declaration or making it a static field
int count = 0;
^^^^^
It also can't declare members named like Object members, because those always dispatch on the run-time object:
extension type Meters(double value) {
@override
String toString() => '$value m';
}
bin/e3b.dart:3:10: Error: This extension member conflicts with Object member 'toString'.
String toString() => '$value m';
^^^^^^^^
The same error appears for == and hashCode. Equality, hashing and toString are always those of the representation. If you need custom ones, use a class. Use a differently named method for display instead, like format() above.
implements: choosing which members to expose
Without an implements clause, an extension type exposes only the members it declares, plus the Object members. With implements, it also gets the members of the types it lists, with no forwarding code. There are three useful forms:
// Transparent: the whole String interface is available.
extension type Html(String source) implements String {
Html wrap(String tag) => Html('<$tag>$source</$tag>');
}
// Implementing a supertype of the representation: only num's members.
extension type Score(int value) implements num {}
// Implementing other extension types.
extension type Id(int value) implements Object {
String get hex => value.toRadixString(16);
}
extension type ProductId(int value) implements Id {
bool get isLegacy => value < 1000;
}
void printLength(String s) => print('length ${s.length}');
void main() {
final h = Html('hi').wrap('b');
print(h);
print(h.toUpperCase()); // String member, returns a String
printLength(h); // Html is a subtype of String
final s = Score(7);
print(s + 0.5); // num.+
// s.isEven; // error: The getter 'isEven' isn't defined for the type 'Score'
final p = ProductId(255);
print(p.hex); // inherited from Id
print(p.isLegacy);
Id general = p; // ProductId is a subtype of Id
print(general.value);
}
Output:
<b>hi</b>
<B>HI</B>
length 9
7.5
ff
true
255
Html implements Stringis transparent: everyStringmember works, and anHtmlcan be passed where aStringis expected. The reverse still needs the constructor, so the type tracks "this string is already HTML". Inherited members return their original types:h.toUpperCase()is aString, not anHtml.Score implements numexposes onlynum's members.isEvenbelongs toint, so it's hidden. Use this to expose a safe subset of the representation's API.ProductId implements IdinheritsId's members and is assignable toId, like a subclass. You can implement several extension types at once, and mix them with non-extension types.
The compiler checks that these relationships are true at run time:
extension type Name(String value) implements int {}
extension type Id(int value) {}
extension type Code(String value) implements Id {}
bin/e5.dart:1:46: Error: The implemented interface 'int' must be a supertype of the representation type 'String' of extension type 'Name'.
bin/e5.dart:3:46: Error: The representation type 'String' of extension type 'Code' must be either a subtype of the representation type 'int' of the implemented extension type 'Id' or a subtype of 'Id' itself.
implements Object
An extension type with no implements clause isn't a subtype of Object, even if its representation is non-nullable. The compiler treats it as possibly nullable:
extension type UserId(int value) {}
extension type AccountId(int value) implements Object {}
void main() {
final u = UserId(1);
Object? a = u; // OK
Object b = u; // error
Object c = AccountId(1); // OK
}
bin/e8.dart:7:14: Error: A value of type 'UserId' can't be assigned to a variable of type 'Object'.
Add implements Object (or implement any non-nullable type) when the value must be usable as a non-null Object, for example as a generic argument bounded by Object.
Redeclaring members with @redeclare
An extension type can declare a member with the same name as one it gets through implements. This redeclares (shadows) the member. It isn't an override, because extension type members are resolved from the static type, never at run time:
import 'package:meta/meta.dart';
extension type PositiveList(List<int> _list) implements List<int> {
@redeclare
void add(int value) {
if (value <= 0) throw ArgumentError.value(value, 'value', 'must be > 0');
_list.add(value);
}
void clear() => _list.clear(); // not annotated: lint warning
}
void addZero(List<int> list) => list.add(0);
void main() {
final nums = PositiveList([1, 2]);
nums.add(3);
try {
nums.add(-1);
} on ArgumentError catch (e) {
print(e.message);
}
addZero(nums); // static type List<int>: List.add runs, no check
print(nums);
}
Output:
must be > 0
[1, 2, 3, 0]
nums.add(-1) calls the extension type's add, which rejects it. Inside addZero the static type is List<int>, so List.add runs and the 0 gets in. A class overriding add would have caught both calls. Treat redeclaration as API convenience, not as a way to enforce an invariant.
@redeclare from package:meta documents the intent. The annotate_redeclares lint flags redeclarations without it:
info - e6.dart:10:8 - The member 'clear' is redeclaring but isn't annotated with '@redeclare'. Try adding the '@redeclare' annotation. - annotate_redeclares
Enable it in analysis_options.yaml:
linter:
rules:
- annotate_redeclares
Zero-cost units
Mixing up meters and seconds, or cents and dollars, is a classic bug. Extension types over double or int prevent it at compile time and cost nothing at run time. Add operators only where the result makes sense:
extension type const Meters(double value) implements Object {
Meters operator +(Meters other) => Meters(value + other.value);
Meters operator *(num factor) => Meters(value * factor);
bool operator <(Meters other) => value < other.value;
MetersPerSecond operator /(Seconds t) => MetersPerSecond(value / t.value);
}
extension type const Seconds(double value) implements Object {}
extension type const MetersPerSecond(double value) implements Object {
double get kmh => value * 3.6;
}
extension Units on num {
Meters get m => Meters(toDouble());
Meters get km => Meters(toDouble() * 1000);
Seconds get s => Seconds(toDouble());
}
const marathon = Meters(42195);
void main() {
final run = 10.km + 500.m;
print(run.value);
print(run < marathon);
final speed = run / 3000.s;
print(speed.kmh.toStringAsFixed(1));
print((run * 2).value);
// run + 3000.s; // error: The argument type 'Seconds' can't be assigned to 'Meters'
}
Output:
10500.0
true
12.6
21000.0
Meters + Meters is allowed, Meters + Seconds isn't, and Meters / Seconds gives a speed. The Units extension methods on num provide the 10.km literals. A List<Meters> is a plain List<double> in memory. With a wrapper class it would be a list of pointers to separate objects. More operator examples are in Operators.
Typed views over JSON
jsonDecode returns Map<String, dynamic> trees, and reading them means string keys and casts everywhere. Extension types can give each part of the tree a typed API without copying it into model objects:
import 'dart:convert';
extension type Order(Map<String, Object?> json) {
String get id => json['id'] as String;
Customer get customer => Customer(json['customer'] as Map<String, Object?>);
List<LineItem> get items => (json['items'] as List).cast<LineItem>();
double get total => items.fold(0, (sum, i) => sum + i.subtotal);
}
extension type Customer(Map<String, Object?> json) {
String get name => json['name'] as String;
String? get email => json['email'] as String?;
}
extension type LineItem(Map<String, Object?> json) {
String get sku => json['sku'] as String;
int get quantity => json['qty'] as int;
double get price => (json['price'] as num).toDouble();
double get subtotal => quantity * price;
set quantity(int q) => json['qty'] = q;
}
const source = '''
{"id": "A-17", "customer": {"name": "Ada"},
"items": [{"sku": "pen", "qty": 3, "price": 1.5},
{"sku": "pad", "qty": 1, "price": 4}]}
''';
void main() {
final order = Order(jsonDecode(source) as Map<String, Object?>);
print(order.customer.name);
print(order.customer.email ?? 'no email');
for (final item in order.items) {
print('${item.sku} x${item.quantity}: ${item.subtotal}');
}
print(order.total);
order.items.first.quantity = 10; // writes through to the map
print(order.total);
print(jsonEncode(order.json['items']));
}
Output:
Ada
no email
pen x3: 4.5
pad x1: 4.0
8.5
19.0
[{"sku":"pen","qty":10,"price":1.5},{"sku":"pad","qty":1,"price":4}]
(json['items'] as List).cast<LineItem>()turns the decoded list into aList<LineItem>without creating any objects. ALineItemis aMap<String, Object?>at run time, so the cast checks each element as a map when it's read.- The setter writes straight into the underlying map, so
jsonEncodesees the change. There's notoJson()to keep in sync. - Nothing is validated up front. A missing key fails with a
TypeErrorwhen its getter runs, not when the JSON is parsed. For untrusted input, validate in a factory constructor, or decode into real classes with JSON serialization.
The same idea applied to nested structures is shown in Nested classes, and dart:js_interop uses it for JavaScript objects.
Erasure pitfalls
Extension types exist only for the static type checker. Everything that runs at run time, such as type tests, casts, switch patterns, dynamic calls and generics, sees the representation type:
extension type UserId(int value) {
String get label => 'user #$value';
}
extension type OrderId(int value) {}
void main() {
final user = UserId(7);
// 1. Type tests see the representation type.
print(user.runtimeType);
Object o = 7;
print(o is UserId); // any int "is" a UserId
print(user is int);
// 2. Casts can't fail if the representation matches.
final order = user as OrderId; // compiles and runs
print(order.value);
// 3. Generic types are erased too.
final ids = <UserId>[UserId(1), UserId(2)];
print(ids.runtimeType);
print(ids is List<OrderId>);
// 4. Switch patterns match the representation.
switch (o) {
case UserId id:
print('matched ${id.label}');
}
// 5. dynamic loses the extension members.
dynamic d = user;
try {
print(d.label);
} on NoSuchMethodError {
print('NoSuchMethodError: label');
}
print(d.isEven); // int members work through dynamic
// 6. Equality and identity are those of the representation.
print(UserId(7) == UserId(7));
print(identical(user, 7));
}
Output:
int
true
true
7
List<int>
true
matched user #7
NoSuchMethodError: label
false
true
true
dart analyze reports no issues for this code, so these mistakes aren't caught for you. Rules of thumb:
- Don't use
is UserIdorcase UserId()to tell aUserIdfrom anOrderId: both are justints. If you need to distinguish them at run time, use classes, or a sealed class hierarchy. as SomeExtensionTypenever validates anything. It skips your factory, so it can produce aPercentof 250. Call the constructor instead.- Don't pass extension-typed values through
dynamicorObject?and expect the members to come back. Keep the static type. - An extension type isn't a security boundary. Anyone holding a
ReadOnlyListcan cast it back toListand modify it, andprint(secret)shows the representation. See Application security.
Extension types vs classes, extensions and typedefs
| extension type | class (wrapper) | extension methods | typedef | |
|---|---|---|---|---|
| new static type | yes | yes | no | no (alias) |
| run-time cost | none | one object per value | none | none |
run-time identity (is, patterns) |
no, erased | yes | n/a | n/a |
| instance fields | no, only the representation | yes | no | n/a |
custom ==, hashCode, toString |
no | yes | no | n/a |
| dispatch | static | virtual (overridable) | static | n/a |
| hides the wrapped type's API | yes, unless implements |
yes | no, only adds members | no |
Pick:
- an extension type for IDs, units, validated strings, typed views over maps or JS objects, and limited APIs over existing values, where performance matters or there are many values
- a class when you need run-time type checks, custom equality or
toString, extra state, overridable behaviour or a guarantee that nobody can bypass the wrapper - extension methods to add helpers to a type for everyone who imports them, without a new type
- a typedef to give a long type (a record or function type) a shorter name. It doesn't create a type: a
typedef UserId = intaccepts anyint
Summary
extension type Name(Rep value) { ... }creates a compile-time-only type over a representation value. At run time the value is just aRep.- Use a private representation constructor plus a factory to validate inputs. Static members, named constructors and
constall work. - No instance fields, and no
toString,==orhashCodeof your own. implements Repforwards the whole interface. Implementing a supertype exposes a subset, and implementing other extension types builds hierarchies. Addimplements Objectto make the type non-nullable.- Redeclared members are resolved statically. Mark them with
@redeclareand turn onannotate_redeclares. is,as, generics, patterns anddynamicall see the representation, so never rely on an extension type at run time.