Skip to main content
A static getter is a class-level method declared with the static and get modifiers that retrieves a value. Unlike instance getters, a static getter is associated with the class definition itself rather than a specific instance of that class. It allows the retrieval of private static fields or the execution of logic to compute a return value without requiring object instantiation.

Syntax

To define a static getter, prepend the static keyword to a standard getter declaration.
class ClassName {
  // Declaration
  static ReturnType get getterName {
    // Logic to retrieve or compute value
    return value;
  }
}

// Access
var value = ClassName.getterName;

Implementation Details

  1. Class Association: The getter is invoked on the class type (e.g., ClassName.property), not on an instance variable.
  2. No Argument List: Like all getters, static getters do not accept parameters and are invoked without parentheses.
  3. Scope Restrictions:
    • No this context: Because the getter is static, it does not have access to the this keyword.
    • No Instance Access: It cannot access instance variables or instance methods. It can only interact with other static members or external constants.
  4. Inheritance: Static getters are not inherited by subclasses and cannot be overridden using the @override annotation.

Code Example

The following example demonstrates a static getter providing read-only access to a private static field.
class ServerConfig {
  // Private static field
  static const String _baseUrl = 'https://api.example.com';

  // Public static getter
  static String get baseUrl {
    return _baseUrl;
  }
  
  // Static getter with computation
  static int get currentTimestamp {
    return DateTime.now().millisecondsSinceEpoch;
  }
}

void main() {
  // Accessing the getter via the Class name
  print(ServerConfig.baseUrl); 
  
  // Accessing a computed static getter
  print(ServerConfig.currentTimestamp);
  
  // Error: Static getters cannot be accessed via an instance
  // var config = ServerConfig();
  // print(config.baseUrl); // Compilation Error
}
Master Dart with Deep Grasping Methodology!Learn More