A private setter in Dart is a mutator method restricted to library-level scope, defined by prefixing the setter’s identifier with an underscore (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.
_). It encapsulates write access to a class property, ensuring that the property can only be mutated by code residing within the same library where the class is declared, while remaining completely inaccessible to external libraries.
In Dart, privacy is strictly library-based, not class-based or strictly file-based. A single library can span multiple .dart files using part and part of directives. Therefore, a private setter is hidden from imported libraries but remains fully invocable by any other class, subclass, or top-level function defined within the same library, regardless of which specific file within that library contains the caller.
Syntax and Implementation
To define an explicit private setter, theset keyword is followed by an underscore-prefixed identifier. Because Dart does not allow a field and a setter to share the exact same name within the same class, a distinct backing variable is required. Explicit private setters are utilized when custom logic—such as validation or side effects—must occur during internal mutation.
Scope and Access Rules
The compiler enforces the visibility of the private setter based strictly on the library boundary, not the file boundary. Within the same library (e.g., apart file):
Technical Characteristics
- Implicit Setters: Declaring a private mutable field (e.g.,
double _value;) automatically generates an implicit private getter and an implicit private setter. An explicit private setter is not required unless the mutation process demands custom execution logic. - Asymmetrical Visibility: Dart does not support asymmetrical visibility modifiers (e.g.,
public get,private set) on a single property identifier. The idiomatic approach to expose read-only access externally while maintaining internal write access is to define a private field (which provides the implicit private setter) alongside a public getter. If custom internal mutation logic is required, developers define a public getter and an explicit private setter (e.g.,set _temperature). Because the compiler evaluates these as separate properties rather than a unified getter/setter pair, compound assignment operators (likesensor.temperature += 10) will fail externally, as the type system cannot route the assignment of the publictemperatureto the private_temperature. - Inheritance: Private setters are not inherited by subclasses if the subclass resides in a different library. If the subclass is declared within the same library, it inherits the private setter and can access or override it.
Master Dart with Deep Grasping Methodology!Learn More





