Extension Operators

Learn to use Dart's Extension Operators.

We'll cover the following

Extension Operators

Dart provides support for operators in addition to methods that we explored in the last lesson. In this lesson, we will add two extension operators: ^ and - on the List type. This list of prices is similar to the last example.

Example #1

Let’s define an operator extension for ^ operator. We can assume this operator increases the price by the n times, where n is the argument passed into it.

Defining:

The operator keyword is used to declare an extension of the type operator and is followed by the operator sign itself. In the following example, the current (this) list is iterated over to multiply each item by n, and the updated list is returned.

extension<T> on List<T> {
  //Extension Operator: Hike up the price by n
  List<num> operator ^(int n) =>
    this.map((item) => num.parse("${item}") * n).toList();

}

Using:

The operator ^ is applied to the list prices. The operator ^ multiplies each item in prices by 3 and returns. The updated list is printed on the console using the print() method.

void main() {
  //List of prices
  List prices = [1, 1.99, 4];

  print("\nPrice listing after hiking up prices 3x of the original value");

  //argument is passed after the operator sign
  print(prices ^ 3);
}

Output: The original list items’ values are updated to 3 times.

Price listing after hiking up prices 3x of the original value
[3, 5.97, 12]

Get hands-on with 1400+ tech skills courses.