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 [] (index) operator in Dart is an overloadable instance method that enables subscript access on objects, allowing them to be queried or mutated using array-like or map-like bracket notation. In Dart, subscripting is not a built-in language primitive restricted to core collections; rather, it is syntactic sugar for standard method invocations. The operator is divided into two distinct method signatures: one for retrieval (operator []) and one for assignment (operator []=).

Syntax and Implementation

To support the index operator, a class must define one or both of the following methods. The following example uses generic type parameters to demonstrate a valid, compilable implementation:
class CustomIndexer<K, V> {
  final Map<K, V> _internalData = {};

  // Handles read access: var x = obj[index];
  V? operator [](K index) {
    return _internalData[index];
  }

  // Handles write access: obj[index] = value;
  void operator []=(K index, V value) {
    _internalData[index] = value;
  }
}

Technical Characteristics

  • Arity Constraints:
    • operator [] must accept exactly one parameter (the index).
    • operator []= must accept exactly two parameters (the index, followed by the value to assign).
  • Type Flexibility: The index parameter is not constrained to integers. It can be any valid Dart type, including String, Enum, or custom objects. This is the underlying mechanism that allows Dart’s Map to accept arbitrary objects as keys.
  • Return Types:
    • operator [] can return any type, including nullable types (T?), which is standard practice when an index might be out of bounds or a key might not exist.
    • operator []= must have a void return type, as the assignment expression evaluates to the assigned value inherently, not via the method’s return.
  • Invocation Translation: The Dart compiler translates bracket notation directly into method calls at compile time. However, unlike standard methods, operator methods cannot be invoked using dot notation with the operator keyword (e.g., instance.operator[](key) is strictly invalid Dart syntax and will cause a compile-time error). They must be invoked using the bracket syntax:
    • var x = instance[key]; conceptually invokes the operator [] method with key as the argument.
    • instance[key] = value; conceptually invokes the operator []= method with key and value as the arguments.
    • To invoke a superclass implementation, Dart provides the explicit super[key] and super[key] = value syntax.
  • Null Safety: If the object being indexed is potentially null, Dart provides the null-aware index operator (?[]), which short-circuits the evaluation to null without throwing a NoSuchMethodError (e.g., var x = instance?[key];).
Master Dart with Deep Grasping Methodology!Learn More