Skip to content
Tutorials Center
My learning

Topics

Lesson 33 of 61 ยท Classes and Object-Oriented Dart

Extension Methods and Extension Types

Learn how Dart extension methods add members to existing types, how to name and scope them, and how extension types wrap a value with zero runtime cost.

Sometimes a class almost does what you need, but you cannot edit it. String, int, List and DateTime belong to the Dart SDK, and classes from packages belong to someone else. You could write a free function such as capitalize(text), but text.capitalize() reads better, shows up in autocomplete and chains naturally.

Dart gives you two tools for this. Extension methods add new members to an existing type. Extension types, added in Dart 3.3, wrap an existing value in a new compile-time type, so that an int that means a user id cannot be confused with an int that means a count. This lesson explains both. The Dart snippets are read-only; the runnable examples are TypeScript stand-ins.

Your first extension

An extension has a name, an on clause naming the type to extend, and a body with methods, getters, setters and operators:

DART
extension StringTools on String {
  String capitalize() {
    if (isEmpty) return this;
    return this[0].toUpperCase() + substring(1);
  }

  bool get isBlank => trim().isEmpty;
}

void main() {
  print('dart'.capitalize());   // Dart
  print('   '.isBlank);         // true
}

Inside the body, this is the object being extended, and you can call its members without a prefix (isEmpty, substring, trim). The call 'dart'.capitalize() looks like a normal method call, but the compiler resolves it statically: it rewrites the call to a plain function call, passing the receiver as an argument.

That static resolution has consequences:

  • An extension cannot add instance fields, because the original class has no room for them. Getters and setters are fine, as long as they compute their value from existing state.
  • If the type already has a member with the same name, the class's own member wins.
  • The extension does not change the object. runtimeType, is checks and toString() of the original are unaffected.
flowchart LR
    C["'dart'.capitalize()"] --> R["Compiler looks up<br/>capitalize on String"]
    R -->|"class member?"| M["Use the class member"]
    R -->|"no, found in<br/>imported extension"| X["Call StringTools.capitalize<br/>with 'dart' as this"]

Extension calls are resolved at compile time from the static type of the receiver.

Extending generics and nullable types

Extensions can be generic and can target specific type arguments:

DART
extension ListStats on List<int> {
  int get total => fold(0, (sum, n) => sum + n);
  double get average => isEmpty ? 0 : total / length;
}

extension Chunking<T> on List<T> {
  List<List<T>> chunked(int size) {
    final result = <List<T>>[];
    for (var i = 0; i < length; i += size) {
      result.add(sublist(i, i + size > length ? length : i + size));
    }
    return result;
  }
}

void main() {
  print([2, 4, 9].average);               // 5.0
  print([1, 2, 3, 4, 5].chunked(2));      // [[1, 2], [3, 4], [5]]
}

ListStats applies only to List<int>, so ['a'].total is a compile error. Chunking<T> works for any element type.

You can also extend a nullable type, which lets you call a method on something that might be null:

DART
extension NullableString on String? {
  bool get isNullOrEmpty => this == null || this!.isEmpty;
}

Here this is a String?, so you must check it before use. Since this cannot be promoted like a local variable, the example uses ! after the null test. Use this technique sparingly, because it hides a null from a reader who expects . to fail on null values. See Null Safety: Nullable and Non-Nullable Types for the background.

TypeScript Adding methods to built-in types (TypeScript stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Naming, scope and conflicts

Extensions have names so you can control them. You can import one selectively (import 'tools.dart' show StringTools;), hide it, or call it explicitly. An extension is only active where its library is imported. If two imported extensions add the same member to the same type, the call is ambiguous and Dart reports an error. Resolve it by applying one explicitly:

DART
print(StringTools('dart').capitalize());

You can omit the name (extension on String { ... }), but an unnamed extension is private to its library and cannot be hidden, shown or called explicitly. Use unnamed extensions only for small helpers inside a single file.

Two other warnings. An extension on dynamic does not apply to dynamic-typed receivers, because static resolution needs a known type. Extension on Object is allowed but pollutes every type, so avoid it. And do not use extensions to hide complicated logic: if the behavior belongs to your own class, put it in the class.

Extension types

An extension type is a different tool. It creates a new type whose runtime representation is an existing value:

DART
extension type UserId(int value) {
  UserId.parse(String text) : value = int.parse(text);

  bool get isValid => value > 0;
}

void greet(UserId id) => print('Hello, user ${id.value}');

void main() {
  final id = UserId(42);
  greet(id);          // fine
  // greet(42);       // error: int is not a UserId
  // print(id + 1);   // error: UserId has no operator +
}

The part in parentheses is the representation type: UserId is stored as a plain int at runtime. There is no wrapper object, so wrapping costs nothing. The compiler, however, treats UserId and int as different types, which prevents mixing up two ids, two prices or a count and a size.

Key differences from extension methods and ordinary classes:

  • An extension type only exposes the members you declare. If you want to forward some of the representation type's members, use implements int (or another supertype). Without it, even + is unavailable.
  • It exists only at compile time. At runtime id is UserId is the same check as id is int, and id.runtimeType reports int. Do not rely on is tests with extension types for safety across dynamic boundaries.
  • You can validate in a constructor body or initializer list (for example a UserId.checked(int v) constructor that throws for v <= 0), but the check applies only where that constructor runs.
  • It cannot have instance fields besides the representation field, and it cannot extend a class.

Pick an extension type to create a distinct, zero-cost type for a primitive or a small object, such as Email, Meters or Milliseconds. Pick an ordinary class when you need identity, additional fields or runtime polymorphism.

TypeScript A zero-cost wrapper type (TypeScript stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. How does Dart decide which extension method to call in 'dart'.capitalize()?

    Extension methods are resolved statically from the type the compiler sees, which is why they cannot be overridden and do not work on dynamic.
  2. 2. Which of these can an extension method NOT do?

    Extensions cannot add instance fields, because the original class has no storage for them. Getters, setters, operators and generics are all allowed.
  3. 3. A class already has a method named capitalize, and an imported extension also defines capitalize. Which one runs?

    Members declared by the type itself always win over extension members with the same name.
  4. 4. What is the main benefit of extension type UserId(int value)?

    An extension type is erased at runtime, so UserId is stored as an int, but the compiler refuses to mix it up with other ints.
  5. 5. Why does id + 1 fail for extension type UserId(int value)?

    An extension type exposes only its own declared members. Add implements int if you want to forward the representation type's members.

Summary

  • extension Name on Type { ... } adds methods, getters, setters and operators to a type you do not own.
  • Extensions are resolved statically, cannot add fields, and lose against members of the type itself.
  • They can be generic, target specific type arguments, or extend a nullable type; names let you show, hide or call them explicitly.
  • Extension types, extension type Name(Repr value), create a new compile-time type with no runtime cost.
  • Use them to separate meanings such as ids, units and validated strings.

Next, teach your own classes how to compare and print themselves in Operator Overloading, ==, hashCode and toString.