Skip to main content
A private setter restricts the mutation of a property to the library in which it is defined. In Dart, privacy is enforced at the library level (typically a single file) rather than the class level, and is denoted syntactically by prefixing an identifier with an underscore (_). To implement a private setter, a developer typically employs a private backing field combined with a public getter. This exposes the value for reading externally while preventing external assignment.

Syntax and Implementation

Dart does not use access modifier keywords like private or protected. Instead, the presence of the underscore determines visibility.

1. The Backing Field Pattern

The most common implementation involves defining a private variable (the backing field) and a public getter. The setter is effectively “private” because the field itself cannot be accessed outside the library.
// library_a.dart
class Session {
  // Private backing field.
  // Only accessible within library_a.dart.
  String _token = '';

  // Public getter.
  // Accessible from any library importing library_a.dart.
  String get token => _token;

  // Internal method mutating the private field.
  void generateNewToken(String seed) {
    _token = 'hashed_$seed'; 
  }
}

2. Explicit Private Setter

While less common, you can explicitly define a setter method with a private identifier. This allows for validation or logic execution when the value is modified internally or by other classes within the same file.
class Configuration {
  int _timeout = 30;

  // Public getter
  int get timeout => _timeout;

  // Explicit private setter
  // Syntax: set _identifier(Type value)
  set _internalTimeout(int value) {
    if (value > 0) {
      _timeout = value;
    }
  }

  void reset() {
    // Invoking the private setter
    _internalTimeout = 60; 
  }
}

Visibility Rules

The Dart compiler enforces the following rules regarding private setters and fields:
  1. Library Scope: A property named _variable is visible to all classes and functions defined within the same .dart file (library).
  2. External Access: Attempting to assign a value to _variable from a different library (a separate file) results in a compilation error: The setter '_variable' isn't defined for the class.

Access Comparison

ContextRead Access (via Public Getter)Write Access (via Private Field/Setter)
Same ClassAllowedAllowed
Same Library (File)AllowedAllowed
External LibraryAllowedCompilation Error
Master Dart with Deep Grasping Methodology!Learn More