Skip to main content
A private getter is a method scoped to the defining library that provides read access to an object property. It is declared using the get keyword followed by an identifier prefixed with an underscore (_). This prefix signals to the Dart compiler that the member is accessible only within the .dart file (library) in which it is defined.

Syntax Declaration

To define a private getter, prepend the property name with an underscore.
class NetworkConfig {
  // Private backing field
  String _apiKey = '12345-ABCDE';

  // Private getter
  // Syntax: ReturnType get _identifier => expression;
  String get _formattedKey => 'Key: $_apiKey';
  
  // Block body syntax
  bool get _isValid {
    return _apiKey.isNotEmpty;
  }
}

Access Mechanics

Private getters are invoked using dot notation without parentheses, identical to public fields or getters. However, visibility is strictly enforced based on the library structure.

1. Intra-Library Access (Valid)

Code residing in the same file (library) can access the private getter, even outside the defining class.
// File: config.dart
class System {
  int get _internalId => 42;
}

void debugSystem() {
  final sys = System();
  
  // Valid: Accessed within the same library
  print(sys._internalId); 
}

2. Extra-Library Access (Invalid)

Code residing in a different file cannot resolve the identifier.
// File: main.dart
import 'config.dart';

void main() {
  final sys = System();
  
  // Compilation Error: The getter '_internalId' isn't defined for the class 'System'.
  // print(sys._internalId); 
}

Technical Characteristics

  • Library Privacy: Unlike Java or C#, Dart privacy is library-level, not class-level. A private getter is visible to any class or function defined in the same file.
  • Computed Properties: Private getters can return values derived from other state rather than simply returning a backing field.
  • No Setter Requirement: A private getter can exist without a corresponding private setter, effectively creating a read-only property within the library scope.
  • Identifier Resolution: The underscore is part of the identifier name. _value and value are treated as distinct symbols by the compiler.
Master Dart with Deep Grasping Methodology!Learn More