Skip to main content
A static setter is a specialized class-level method that acts as a mutator for static state. It enables the execution of logic during the assignment of a value to a static property while utilizing the syntax of variable assignment rather than method invocation.

Syntax

class ClassName {
  static set propertyName(Type parameter) {
    // Logic to execute on assignment
  }
}

Technical Mechanics

  • Declaration: Defined using the static modifier followed by the set keyword.
  • Invocation: Accessed directly through the class identifier, not an object instance (e.g., ClassName.property = value).
  • Context: Operates within a static context. It has no access to the this keyword or instance-level members. It can only interact with other static members, top-level variables, or literals.
  • Parameters: Must accept exactly one required argument.
  • Return Type: The return type is implicitly void and cannot be explicitly declared.

Implementation Example

The following example demonstrates a static setter controlling the assignment of a private static backing field.
class SystemSettings {
  // Private static backing field
  static int _maxConnections = 5;

  // Static setter
  static set maxConnections(int value) {
    // Logic: Validation before assignment
    if (value <= 0) {
      throw ArgumentError('Connections must be greater than zero.');
    }
    _maxConnections = value;
  }

  // Static getter for verification
  static int get maxConnections => _maxConnections;
}

void main() {
  // Invoking the static setter using assignment syntax
  SystemSettings.maxConnections = 10;

  print(SystemSettings.maxConnections); // Output: 10
}
Master Dart with Deep Grasping Methodology!Learn More