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 private getter in Dart is an accessor function prefixed with an underscore (_) that provides read access to a property or computed value, while restricting its visibility strictly to the library (file) in which it is declared. Because Dart enforces privacy at the library level rather than the class level, a private getter is accessible to any code within the same file, but completely hidden from external imports.

Syntax

A private getter is defined using the get keyword, followed by an identifier that must begin with an underscore. It takes no parameters. Arrow Syntax (Expression Body):
ReturnType get _identifier => expression;
Block Syntax:
ReturnType get _identifier {
  return expression;
}

Technical Mechanics

  • Invocation: Although declared as a function, a getter is evaluated like a standard property. It is accessed without parentheses ().
  • Parameterless: By definition in the Dart language specification, getters cannot accept arguments.
  • Library-Bound Privacy: The _ prefix makes the getter private to the .dart file, not the enclosing class. If ClassA and ClassB are declared in the same file, ClassB can access ClassA’s private getters.
  • Setter Pairing: A private getter can be paired with a private setter using the exact same identifier (e.g., get _value and set _value) to form a logically mutable private property.

Code Visualization

The following example demonstrates the declaration and library-level scoping of a private getter:
// file: data_model.dart

class DataModel {
  final List<String> _records = ['A', 'B', 'C'];

  // Private getter using arrow syntax
  int get _recordCount => _records.length;

  // Private getter using block syntax
  String get _lastRecord {
    if (_records.isEmpty) return 'None';
    return _records.last;
  }

  void debugPrint() {
    // Accessed internally without parentheses
    print("Count: $_recordCount"); 
  }
}

// Top-level function in the SAME library (file)
void inspectData() {
  final model = DataModel();
  
  // VALID: Private getters are accessible within the same library
  print(model._recordCount); 
  print(model._lastRecord);
}
If the DataModel class above were imported into a different file, attempting to access model._recordCount would result in a compile-time error: The getter '_recordCount' isn't defined for the class 'DataModel'.
Master Dart with Deep Grasping Methodology!Learn More