Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

A public getter in Dart is a specialized method that provides read access to an object’s state or computed properties using field-access syntax. In Dart, identifiers are public by default; therefore, a getter is public as long as its name does not begin with an underscore (_).

Implicit Public Getters

When you declare a public instance variable, Dart automatically generates an implicit public getter for it.
class User {
  String username = 'admin'; // Implicit public getter generated
}

void main() {
  final user = User();
  print(user.username); // Invokes the implicit getter
}

Explicit Public Getters

Explicit public getters are defined using the get keyword. They allow you to define custom logic for property retrieval, such as computing a value dynamically or exposing a private field, while maintaining the syntactic footprint of a standard field access.

Syntax

An explicit getter is declared with an optional return type, the get keyword, and the identifier, followed by either a block body or an arrow function. It strictly takes no parameters and omits the parameter list parentheses (). Arrow Syntax:
ReturnType get propertyName => expression;
Block Body Syntax:
ReturnType get propertyName {
  // computation
  return value;
}

Code Example

class Rectangle {
  double width;
  double height;
  
  // Private variable
  final double _borderWidth = 2.0;

  Rectangle(this.width, this.height);

  // Explicit public getter (Computed property)
  double get area => width * height;

  // Explicit public getter (Exposing private state)
  double get border => _borderWidth;
}

void main() {
  final rect = Rectangle(10.0, 5.0);
  
  // Accessed without parentheses, identical to field access
  print(rect.area);   
  print(rect.border); 
}

Technical Characteristics

  • Parameterless: A getter cannot define any parameters. Attempting to add parentheses () to a getter declaration results in a compilation error.
  • Uniform Access Principle: Because both implicit and explicit getters are invoked using dot notation (object.property), you can change a standard public field into an explicit getter later without breaking the API or requiring changes to the calling code.
  • Scope: Public getters can be declared at the top level of a library, or within classes, mixins, enums, and extensions.
  • Read-Only Enforcement: Defining an explicit getter without a corresponding explicit setter (set) creates a read-only property from the perspective of the caller. Attempting to assign a value to it will result in a compilation error.
  • Overriding: Explicit getters can override implicit getters (fields) from a superclass, and vice versa.
Master Dart with Deep Grasping Methodology!Learn More