- Dart extensions allow you to add new functionality to existing classes, including classes that you don't have access to modify.
Example:
extension StringExtension on String {
int customLength() {
return this.length * 2;
}
}
void main() {
String myString = "Hello";
print(myString.customLength());
}
output:
10
extension int:
extension IntExtension on int {
bool isEvenNumber() {
return this % 2 == 0;
}
}
void main() {
var num = 15;
print("Is ${num} an Even Number? ${num.isEvenNumber()}");
}
extension double:
extension DoubleExtension on double {
double roundToDecimalPlaces(int decimalPlaces) {
double mod = 10.0;
return ((this * mod).round()) / mod;
}
}
void main() {
final pi = 3.14159;
print('Pi rounded to two decimal places: ${pi.roundToDecimalPlaces(2)}');
}
extension Bool:
extension BoolExtension on bool {
int toInt() {
return this ? 1 : 0;
}
}
void main() {
var isTrue = true;
print("The boolean value 'true' converted to integer: ${isTrue.toInt()}");
}