Extension Properties

This lesson explains how to use extension properties. You will also learn that extension methods are static.

Extension Property

Dart provides support for Properties in addition to the methods and operators which we explored in the last few lessons.

In this lesson, we will learn to declare the extension property. We will use the same price list from the previous lessons’ examples.

Example

In this extension, we will add a property to return the total number of printed price labels that are needed for the given price listing. Assume we need to print 3 labels for each price amount in this list [1, 1.99, 4].

Defining:

An extension property definition has three parts: type of data to be returned by the property, the get keyword, and the name of the property. This is followed by the implementation to calculate the result for the property. It should look like this:

<return_type> get <property_name> => //implementation

In our example, the number of labels is of type int. The property name is labelCount. We need 3 labels for each item on the list, therefore, 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 of the given list.

extension<T> on List<T> {
  //Extension Property: 3 printed labels for each price.
  int get labelCount => length * 3;
}

Using:

The property labelCount is called on the price listing prices to find the total number of printed labels.

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

  print("\nNumber of Printed Labels:");
  print(prices.labelCount);
}

Output: Since there are 3 items on the list, the total number of printed labels is 9.

Number of Printed Labels:
9

Get hands-on with 1200+ tech skills courses.