Extension operators#
Dart also provides support for operators. Below, we will define an operator extension for the ^ operator. We assume this operator increases the price by n times, where n is the passed argument.
The operator keyword declares an extension operator, and the operator sign follows it. In the following example, this list is iterated to multiply each item by n, and then 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();
}
The operator ^ is applied to the prices list. The operator ^ multiplies each item in prices by 3 and returns. The updated list is then printed 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);
}
This gives us the output below:
Price listing after hiking up prices 3x of the original value
[3, 5.97, 12]
Extension property#
Dart also provides support for properties. In the extension below, we add a property that returns the total number of printed price labels needed for a price listing. Let’s assume we want to print 3 labels for each price amount in the list [1, 1.99, 4].
An extension property definition has three parts: the type of data to be returned by the property, the get keyword, and the property name. For example:
<return_type> get <property_name> => //implementation
The number of labels is type int, and the property name is labelCount. We need 3 labels for each item, so we need three times the total size of the list. We can calculate the number of total labels as length * 3. The extension has implicit access to the length property.
extension<T> on List<T> {
//Extension Property: 3 printed labels for each price.
int get labelCount => length * 3;
}
The property labelCount is called on the price listing prices.
void main() {
//List of prices
List prices = [1, 1.99, 4];
print("\nNumber of Printed Labels:");
print(prices.labelCount);
}
This gives us the following output:
Number of Printed Labels:
9