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.
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.