Skip to main content
A public getter is a special method that provides read access to an object’s property. In Dart, getters are invoked using dot notation without parentheses, making the invocation syntactically identical to accessing a public field.

Types of Getters

Dart supports two mechanisms for defining public getters: implicit and explicit.

1. Implicit Getters

For every public instance variable declared in a class, Dart automatically generates a corresponding implicit getter. This getter returns the value currently stored in the variable.
class Container {
  // Dart implicitly creates a getter for 'capacity'
  int capacity = 10; 
}

void main() {
  var box = Container();
  // Accessing the implicit getter
  print(box.capacity); 
}

2. Explicit Getters

Explicit getters are defined using the get keyword. They allow the execution of logic or the calculation of values at the time of access. Explicit getters are often used to expose private fields (e.g., _variable) or to create computed properties. Syntax:
ReturnType get propertyName {
  // logic
  return value;
}
Example:
class Circle {
  double radius;

  Circle(this.radius);

  // Explicit getter using block syntax
  double get area {
    return 3.14159 * radius * radius;
  }

  // Explicit getter using arrow syntax (shorthand)
  double get diameter => radius * 2;
}

void main() {
  var c = Circle(5);
  
  // Invoked without parentheses '()'
  print(c.area);     
  print(c.diameter); 
}

Technical Characteristics

  • Invocation: Getters are accessed as properties (obj.prop), not as methods (obj.prop()). Adding parentheses results in a compilation error unless the returned value is itself a callable object (like a Function).
  • Type Safety: The return type of the getter defines the type of the property when accessed. If the return type is omitted, it defaults to dynamic, though type inference usually applies.
  • No Parameters: A getter cannot accept arguments. If arguments are required for retrieval, a standard method must be used instead.
  • Override: An explicit getter can override an implicit getter (a public field) from a superclass, effectively replacing the storage field with a computed method in the subclass.
Master Dart with Deep Grasping Methodology!Learn More