IntermediateDart Questions
What are extension methods in Dart?
Short Answer
Extension methods let you add new functionality to an existing type — including types you don't own, like String or int — without modifying its source or subclassing it.
Normally, to add a method to a class you either edit its source or create a subclass. Extensions sidestep both: you declare `extension <Name> on <Type> { ... }` and any method or getter inside becomes callable on instances of that type, as if it were built in.
Extensions are resolved statically at compile time based on the declared type of the variable, not its runtime type, and they only apply where the extension is imported and visible — there's no global mutation of the type happening.
Code Example
extension StringCasingExtension on String {
String capitalize() =>
isEmpty ? this : '${this[0].toUpperCase()}${substring(1)}';
}
void main() {
print('flutter'.capitalize()); // "Flutter"
}Common Mistakes
- ×Assuming extension methods are dynamically dispatched like normal instance methods — they're resolved by static type.
- ×Defining two extensions with conflicting method names on the same type and being surprised by ambiguity errors.