Dart Extension Method

Dart Extension Method

  • 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
}

output:

10

extension int:

extension IntExtension on int {
  // Example extension method to check if the number is even
  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 {
  // Example extension method to round a double to a specified number of decimal places
  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 {
  // Example extension method (not really useful, just for demonstration)
  int toInt() {
    return this ? 1 : 0;
  }
}

void main() {
  var isTrue = true;
  print("The boolean value 'true' converted to integer: ${isTrue.toInt()}");
}