CodeBlanks Logo Icon CodeBlanks

What are extensions?

Learn the Dart extension concept.

What are extensions?

Extension lets you add new methods or properties to an existing type (class, record, list). You add functionality from outside without subclassing. The extension StringOps on String { ... } declaration adds new methods to String.

Extensions are especially useful for adding functionality to types you don't own (library classes, dart:core types). Extension methods are resolved statically; that is, the called method is determined at compile time.

Extension syntax

An extension is declared with extension Name on Type { ... }. Name is the extension's name, Type is the extended type. Methods, getters, and setters are declared inside the curly braces.

For example, extension NumberOps on int { int square() => this * this; } adds a square() method to int. Usage is 5.square(). The extension name avoids conflicts; it doesn't affect the code.

Practice A StringEcho extension

Define a StringEcho extension on String with a String echo() => '$this $this'; method. In main add print('Hello'.echo());.

Starter code

main.dart
void main() {
  // define a StringEcho extension (on String; echo method)
  // print 'Hello'.echo()
}

Sample solution

main.dart
extension StringEcho on String {
  String echo() => '$this $this';
}

void main() {
  print('Hello'.echo());
}

Expected output

Hello Hello

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does an extension provide?

  • Does runtime type checking
  • Creates a new class
  • Changes the garbage collector
  • Adds new methods to an existing type Correct answer

Explanation: an extension adds new methods to an existing type from outside.

2 An extension declaration

Question
extension NumberOps on ____ {
  int square() => this * this;
}
Answer
extension NumberOps on int {
  int square() => this * this;
}

Explanation: extension NumberOps on int applies to the int type.

3 Match the extension parts

Term Meaning
extension Declaration keyword
on Target type binder
Name Extension name
Type Extended type

All lessons in Expert