What are Extension Methods?
Extension methods let you add new functionality to existing classes — including built-in types like String, int, List — without modifying or subclassing them. They are purely syntactic sugar: the compiler converts the call to a static function call.
Syntax
extension ExtensionName on ExistingType {
ReturnType newMethod() {
// 'this' refers to the instance
return ...;
}
}
Example
extension StringExtension on String {
String capitalize() {
if (isEmpty) return this;
return this[0].toUpperCase() + substring(1).toLowerCase();
}
bool get isValidEmail => contains('@') && contains('.');
String repeat(int times) => this * times;
}
void main() {
print('hello'.capitalize()); // Hello
print('WORLD'.capitalize()); // World
print('user@example.com'.isValidEmail); // true
print('ha'.repeat(3)); // hahaha
}
Output:Hello
World
true
hahaha
Extending Built-in Types
extension IntExtension on int {
bool get isEven => this % 2 == 0;
bool get isOdd => this % 2 != 0;
int get squared => this * this;
List<int> to(int end) => List.generate(end - this + 1, (i) => this + i);
}
extension ListExtension<T> on List<T> {
T? get secondOrNull => length >= 2 ? this[1] : null;
}
void main() {
print(7.isOdd); // true
print(4.squared); // 16
print(1.to(5)); // [1, 2, 3, 4, 5]
var items = ['a', 'b', 'c'];
print(items.secondOrNull); // b
}
🧠 Quiz
1. What does extension methods let you do?
- A) Modify a class's source code
- B) Add methods to existing types without subclassing ✅
- C) Override existing methods
- D) Make classes immutable
2. Inside an extension method, what does this refer to?
- A) The extension itself
- B) The class being extended
- C) The instance on which the method is called ✅
- D) null
Summary
Extension methods add new methods to existing types using the extension on syntax. Use this to access the instance. They work on built-in types, third-party types, and your own classes. Extensions make code more expressive without modifying the original class.