Skip to main content
The [] operator, formally known as the subscript operator, is a special instance method that enables indexed read access to an object. It allows an instance to be queried using bracket notation, functioning as syntactic sugar for a method call that accepts a single argument (the index or key) and returns a value.

Syntax Definition

To implement the subscript operator in a class, define a method named [] with the operator keyword.
ReturnType operator [](IndexType index) {
  // Logic to retrieve value based on index
  return value;
}
  • ReturnType: The data type of the value returned by the operation.
  • IndexType: The data type of the key used to look up the value (commonly int for sequences or Object for hash maps).

Operational Mechanics

When the Dart compiler encounters an expression like object[key], it translates the syntax into a direct method invocation on object.
  1. Expression: var x = myObject[i];
  2. Translation: var x = myObject.[](i);
The operator is strictly unary regarding the index; it accepts exactly one argument within the brackets.

Implementation Example

The following example demonstrates how to overload the [] operator within a custom class to expose internal data.
class ByteBuffer {
  final List<int> _data;

  ByteBuffer(this._data);

  // Operator definition
  // Accepts an integer index and returns the integer at that position
  int operator [](int index) {
    if (index < 0 || index >= _data.length) {
      throw RangeError.index(index, _data);
    }
    return _data[index];
  }
}

void main() {
  final buffer = ByteBuffer([10, 20, 30, 40]);

  // Invoking the [] operator via bracket notation
  final byte = buffer[2]; 
  
  print(byte); // Output: 30
}

Relationship with []=

The [] operator is exclusively for read access. To enable indexed write access (assignment), the class must also implement the corresponding []= (index assignment) operator.
  • Read: var val = obj[i]; invokes operator [](i)
  • Write: obj[i] = val; invokes operator []=(i, val)
Master Dart with Deep Grasping Methodology!Learn More