Extension methods
suggest changeExtension methods allow you to add new functionality (methods, getters, setters, and operators) to existing classes and types without modifying their original source code or creating subclasses.
Declaring an Extension
Declare an extension using the extension keyword followed by an optional name and the on clause specifying the target type:
extension StringExtensions on String {
// Method
String capitalize() {
if (isEmpty) return this;
return '${this[0].toUpperCase()}${substring(1)}';
}
// Getter
bool get isNumeric {
return double.tryParse(this) != null;
}
// Method with arguments
String truncate(int maxLength) {
if (length <= maxLength) return this;
return '${substring(0, maxLength)}...';
}
}
void main() {
String text = 'hello world';
// Call extension methods like regular instance methods:
print(text.capitalize()); // Hello world
print('42'.isNumeric); // true
print(text.truncate(5)); // hello...
}
Generic Extensions
You can define extensions on generic types and collections. Use type parameters to write reusable utilities:
extension ListExtensions<T> on List<T> {
// Safe element access returning null instead of throwing RangeError
T? elementAtOrNull(int index) {
if (index < 0 || index >= length) return null;
return this[index];
}
// Splitting a list into fixed-size chunks
List<List<T>> chunk(int size) {
List<List<T>> chunks = [];
for (int i = 0; i < length; i += size) {
chunks.add(sublist(i, (i + size > length) ? length : i + size));
}
return chunks;
}
}
void main() {
var numbers = [1, 2, 3, 4, 5];
print(numbers.elementAtOrNull(10)); // null
print(numbers.chunk(2)); // [[1, 2], [3, 4], [5]]
}
Extensions on Nullable Types
You can define extensions specifically on nullable types to handle null safely without requiring manual null checks on every call site:
extension NullableStringExtensions on String? {
bool get isNullOrBlank {
return this == null || this!.trim().isEmpty;
}
}
void main() {
String? a = null;
String? b = ' ';
String? c = 'Dart';
print(a.isNullOrBlank); // true
print(b.isNullOrBlank); // true
print(c.isNullOrBlank); // false
}
Resolving Name Conflicts
If two imported libraries declare extensions with the same method name on the same type, you can resolve the ambiguity using explicit extension invocation syntax:
// Suppose LibraryA and LibraryB both define `parse()` on String:
import 'library_a.dart';
import 'library_b.dart';
void main() {
String input = '123';
// Explicitly specify which extension to apply:
var resultA = ExtensionA(input).parse();
var resultB = ExtensionB(input).parse();
}
Alternatively, use show or hide in your import directive to prevent conflicts:
import 'library_b.dart' hide ExtensionB;
Static Resolution
Extension methods are resolved statically at compile time based on the static type of the variable, not dynamically at runtime:
class Animal {}
class Dog extends Animal {}
extension AnimalExt on Animal {
String speak() => 'Generic animal sound';
}
extension DogExt on Dog {
String speak() => 'Woof!';
}
void main() {
Animal myPet = Dog();
// Prints "Generic animal sound" because the static type of myPet is Animal:
print(myPet.speak());
// Cast to Dog to invoke DogExt:
print((myPet as Dog).speak()); // Woof!
}