Extension Methods
Extension methods allow you to add functionality to existing classes without modifying them.
Extension methods allow you to add functionality to existing classes without modifying them.
extension StringExtension on String {
String get reversed => split('').reversed.join();
String capitalize() {
if (isEmpty) return this;
return '${this[0].toUpperCase()}${substring(1)}';
}
bool get isEmail => contains('@') && contains('.');
}
void main() {
print('hello'.reversed); // olleh
print('dart'.capitalize()); // Dart
print('test@example.com'.isEmail); // true
}extension IntExtension on int {
bool get isEven => this % 2 == 0;
bool get isOdd => this % 2 != 0;
int get squared => this * this;
}
extension ListExtension<T> on List<T> {
T? get secondOrNull => length > 1 ? this[1] : null;
}
void main() {
print(4.isEven); // true
print(5.squared); // 25
print([1, 2, 3].secondOrNull); // 2
}extension DateTimeExtension on DateTime {
bool get isToday {
final now = DateTime.now();
return year == now.year && month == now.month && day == now.day;
}
String get formatted => '$year-$month-$day';
}
void main() {
var now = DateTime.now();
print(now.isToday); // true
print(now.formatted); // 2024-01-15
}