DartIntermediate 2 min read

Dart extension methods and operators: make an ID readable

Add a focused helper to an existing type without pretending to change its runtime class.

On this page

An extension method can make a repeated conversion read naturally without modifying a library’s type. Keep it domain-specific and avoid generic names that collide with other packages. Extension lookup uses the static type at the call site.

Worked example

Language requirement: Dart 3.0 or later. This complete example uses browser-supported libraries.

main.dart
extension OrderIdText on int {
  String get orderLabel => 'ORD-${toString().padLeft(4, '0')}';
}

class Quantity {
  const Quantity(this.value);
  final int value;
  Quantity operator +(Quantity other) => Quantity(value + other.value);
}

void main() {
  print(42.orderLabel);
  final combined = const Quantity(2) + const Quantity(3);
  print(combined.value);
}

Follow the data and control flow

The extension adds readable syntax when the static receiver type is int. It does not attach a new method to every int object’s runtime dispatch table. A dynamic receiver will not automatically discover the extension.

The custom plus operator is an ordinary method contract with familiar syntax. It creates a new value rather than mutating either operand. Define operators only when their meaning is predictable for the domain; a named method is better for a surprising business operation.

A mistake to avoid

Formatting an order label does not establish a unique database ID. Keep identity generation separate. If two extensions provide the same member, resolve imports or use an explicit extension application rather than relying on accidental library order.

Practice and verification

Add a receiver typed as Object and observe why the helper is unavailable until its type is narrowed. Add a named quantity-validation factory. Decide whether adding two quantities with different units should be allowed or rejected.

How this topic connects

Apply it next

Lesson progressMark complete after checking the example and exercise.

Dart extension methods · Flutter · official channel

Preview image only. YouTube loads when you press Play.

A conceptual companion linked from the official Dart extension-method guide. Use the lesson for current source and static-type limitations. Watch on YouTube

Find your next idea

Search lessons, code examples and projects.

Type a few words to start exploring.