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.

The []= operator, formally known as the index assignment operator, is a syntactic mechanism in Dart used to mutate the state of an object at a specified index or key. When the Dart compiler encounters this operator, it translates the assignment expression into an invocation of the underlying operator []= method.
void main() {
  List<String> items = ['a', 'b', 'c'];
  int index = 1;
  String value = 'z';
  
  // Standard assignment syntax
  items[index] = value; 
}

Technical Characteristics

  • Arity and Parameters: The operator []= method requires exactly two parameters. The first parameter represents the index or key (an expression evaluated to determine the target location), and the second parameter represents the value being assigned.
  • Type Flexibility: The static types of both the index/key expression and the value are arbitrary and defined by the implementing class. For example, in a List<T>, the index expression must evaluate to an int and the value to T. In a Map<K, V>, the key expression evaluates to K and the value to V.
  • Return Type: The return type of the operator []= method must be void (attempting to return a value results in a compile-time error). While modern Dart linting practices strongly recommend explicitly declaring the void keyword, the compiler does not strictly require it to be written. Note that the assignment expression itself evaluates to the assigned value (allowing chained assignments like a[0] = b[0] = 5), even though the underlying operator method returns nothing.

Custom Implementation

Dart allows developers to overload the []= operator within custom classes to define proprietary index assignment behavior. This is achieved by declaring a method named operator []=.
class Grid {
  final List<int> _data = List.filled(100, 0);

  // Overloading the index assignment operator
  // Parameter 1: The index/key expression (int)
  // Parameter 2: The value to assign (int)
  void operator []=(int index, int value) {
    if (index < 0 || index >= _data.length) {
      throw RangeError.index(index, _data);
    }
    _data[index] = value;
  }
}

void main() {
  Grid myGrid = Grid();
  myGrid[10] = 255; // Invokes the custom operator []=
}

Null-Aware Assignment

The []= operator interacts with Dart’s null safety features. If the target object is potentially null, Dart utilizes a distinct null-aware index operator (?[]) to safely perform the assignment. This prevents runtime exceptions by short-circuiting the evaluation if the receiver is null.
void main() {
  List<int>? collection;
  int index = 0;
  int value = 42;

  // If 'collection' is null, the assignment is bypassed.
  // If 'collection' is non-null, operator []= is invoked.
  collection?[index] = value;
}
Master Dart with Deep Grasping Methodology!Learn More