Skip to main content
An abstract getter is a property accessor declared within an abstract class or mixin that defines a return type and name but omits the implementation body. It establishes a contractual obligation for concrete subclasses to provide a specific value or computation logic for that property.

Syntax

An abstract getter is declared using the get keyword, followed by the property name, and terminated with a semicolon ; instead of a code block { ... } or arrow syntax =>.
abstract class Vehicle {
  // Abstract getter declaration
  // Defines the signature: returns a double
  double get maxSpeed; 
}

Implementation Mechanics

Concrete subclasses must override the abstract getter to instantiate the class. Dart allows two distinct mechanisms to satisfy this contract:

1. Implementation via Getter

The subclass provides a concrete getter method with a function body that calculates or retrieves the value.
class Car extends Vehicle {
  @override
  double get maxSpeed {
    return 120.0; // Logic to return the value
  }
}

2. Implementation via Field

The subclass declares a field (variable) with the same name and compatible type. In Dart, fields implicitly generate a getter (and a setter if not final). Therefore, a field declaration satisfies the abstract getter contract.
class Truck extends Vehicle {
  // A final field implicitly creates a 'get maxSpeed' accessor
  @override
  final double maxSpeed;

  Truck(this.maxSpeed);
}

Type Constraints

The overriding implementation in the concrete class must adhere to Dart’s type safety rules:
  • The return type must be the same as, or a subtype of, the return type defined in the abstract getter.
  • If the abstract getter is nullable (e.g., int? get value;), the implementation may return a non-nullable type.
  • If the abstract getter is non-nullable, the implementation must return a non-nullable type.
Master Dart with Deep Grasping Methodology!Learn More