Dart Extensions Methods: String , Int , Boolean

Dart Extensions Methods: String , Int , Boolean

What are Extension Methods?

An extension method is a feature in Dart that allows us to add new methods to existing classes or interfaces without changing their original source code. These methods can be used as if they were part of the original class. In other words, extensions enable us to add functionality to a class or interface that they did not write and don’t control.

An extension method is a static method defined within a class that has a receiver parameter. The receiver parameter is the object to which the method is applied. The syntax for declaring an extension method is as follows:

  • Syntax

      extension ExtensionName on ClassName { 
          ReturnType methodName(ParameterType parameter) { 
              // implementation 
          } 
      }
    

    In this syntax, the ExtensionName is the name of the extension and the ClassName is the name of the class being extended. The ReturnType is the type of the value returned by the extension method. The methodName is the name of the method being added, and ParameterType is the type of the parameter being passed to the method.

Let's understand with String Example.

void main(){
  String name = "Vinit";
  print("HELLO ${name.greet()}");
}

extension StringExtension on String{
  String greet(){
    return this.toUpperCase();
  }
}

Let's understand with Int Example.

extension on int {
  // note: `this` refers to the current value
  int add() 
  {
    return this*2;
  }
}

void main()
{
int num = 30;
print('The Value of two number is ${num.add()}');
}

Let's understand with Double Example.

extension on double {
  // note: `this` refers to the current value
  double celsiusToFarhenheit() => this * 1.8 + 32;
  double farhenheitToCelsius() => (this - 32) / 1.8;
}

void main()
{
double tempCelsius = 20.0;
double tempFarhenheit = tempCelsius.celsiusToFarhenheit();
print('${tempCelsius}C = ${tempFarhenheit}F');
}

Did you find this article valuable?

Support Vinit Mepani (Flutter Developer) by becoming a sponsor. Any amount is appreciated!