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 public setter in Dart is a specialized method that provides write access to an object’s property. By default, any setter defined without a leading underscore (_) is public, meaning it is accessible from anywhere the object’s library is imported. Setters are invoked using the assignment operator (=) rather than standard method invocation syntax. Dart implements setters in two ways: implicitly and explicitly.

Implicit Public Setters

Whenever you declare a mutable, non-final public instance variable, the Dart compiler automatically generates an implicit public setter for it.
class DataModel {
  // Generates an implicit public setter: set value(int x)
  int value = 0; 
}

Explicit Public Setters

An explicit public setter is defined using the set keyword. It is typically used to intercept the assignment operation to execute logic before mutating a private backing field.

Syntax

set propertyName(Type parameterName) {
  // Assignment logic
}

Technical Constraints and Characteristics

  • Return Type: Setters do not return a value. While explicitly declaring a void return type (e.g., void set propertyName(...)) is valid syntax and will compile, omitting the return type entirely is the recommended Dart style convention and is enforced by the avoid_return_types_on_setters lint rule.
  • Parameters: A setter must accept exactly one required positional parameter. It cannot accept optional, named, or multiple parameters.
  • Naming: A setter cannot share a name with a method, variable, or getter in the same class, except for its corresponding getter. It is conventionally named after the logical property it mutates, while the actual data is stored in a private backing variable (prefixed with _).
  • Invocation: Setters are called via property access syntax, not method syntax.

Implementation Example

class Measurement {
  // Private backing field
  double _magnitude = 0.0;

  // Explicit public setter
  set magnitude(double value) {
    _magnitude = value;
  }
}

void main() {
  var measure = Measurement();
  
  // Invokes the public setter using the assignment operator
  measure.magnitude = 42.5; 
  
  // INVALID: measure.magnitude(42.5);
}

Arrow Syntax

For setters containing a single expression, Dart supports the concise arrow (=>) syntax.
class Measurement {
  double _magnitude = 0.0;

  // Public setter using arrow syntax
  set magnitude(double value) => _magnitude = value;
}
Master Dart with Deep Grasping Methodology!Learn More