Michele Volpato

Michele Volpato

When to use a getter vs a method in Dart

Dart

Dart provides the possibility to use getters and setters, special methods that give read and write access to an object’s properties.

You can use a getter to hide write access to a property:

enum ProductType { normal, offer }

class Product {
  // The product id.
  final String id = "ABC1234";
  
  // This property cannot be modified directly from outside the object.
  ProductType _type;
  
  Product(this._type);
  
  // _type can be accessed read-only using this getter.
  ProductType get type => _type;
}

You can also use them to calculate a certain value that is not directly stored in your object:

  ...
  
  // Get whether the type of the product is an offer.
  bool get isOffer => _type == ProductType.offer;
 }

You could also use a method, instead of a getter:

  ...
  
  // Get whether the type of the product is an offer.
  bool isOffer() => _type == ProductType.offer;
 }

So, how do you know where to use a getter and where to use a method?

Personally, I avoid using a getter when the value cannot be calculated in O(1). The reason is that a getter and a property look the same from the outside, from the point of view of the user of your object.

final product = Product(ProductType.offer);

// Is this a getter or a property?
product.id;

// Is this a getter or a property?
product.isOffer;

So the fact that there is a calculation behind the getter might be lost for the final user of the object who might think that the getter is a property and will use it as a O(1) “function”.

Get a weekly email about Flutter

Subscribe to get a weekly curated list of articles and videos about Flutter and Dart.

    We respect your privacy. Unsubscribe at any time.

    Leave a comment