Skip to main content
A public setter is a special method declared with the set keyword that provides write access to a property from outside its defining library. It functions as a mutator, encapsulating assignment logic while preserving the syntactic interface of a standard variable assignment.

Syntax

A setter is defined using the set keyword followed by the property name and a parameter list containing exactly one argument.
set propertyName(DataType parameter) {
  // Logic to execute upon assignment
  _backingField = parameter;
}

Technical Characteristics

  • Keyword: The declaration must utilize the set modifier.
  • Parameters: The method signature must accept exactly one required parameter. Optional positional or named parameters are not permitted.
  • Return Type: The return type is strictly void. While Dart syntax permits explicitly writing void before the set keyword (e.g., void set value(...)), it is redundant and typically omitted.
  • Backing Field: Explicit setters are often used to update a private instance variable (conventionally denoted by an underscore _) that holds the object state.
  • Implicit Setters: For every public instance variable that is not declared final, Dart automatically generates an implicit public setter. (Note: const variables are implicitly static and do not generate instance setters).

Implementation Example

The following example demonstrates an explicit setter that modifies a private backing field.
class DataContainer {
  // Private backing field
  double _value = 0.0;

  // Public Setter
  set value(double input) {
    // The setter body executes when the property is assigned
    _value = input; 
  }

  // Public Getter (required to read the value)
  double get value => _value;
}

Invocation

Although defined as a method, a setter is invoked using the assignment operator (=) rather than method call syntax (()).
void main() {
  var container = DataContainer();

  // Invokes the 'value' setter
  container.value = 42.5; 
}
Master Dart with Deep Grasping Methodology!Learn More