[] 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: The data type of the value returned by the operation.IndexType: The data type of the key used to look up the value (commonlyintfor sequences orObjectfor hash maps).
Operational Mechanics
When the Dart compiler encounters an expression likeobject[key], it translates the syntax into a direct method invocation on object.
- Expression:
var x = myObject[i]; - Translation:
var x = myObject.[](i);
Implementation Example
The following example demonstrates how to overload the[] operator within a custom class to expose internal data.
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];invokesoperator [](i) - Write:
obj[i] = val;invokesoperator []=(i, val)
Master Dart with Deep Grasping Methodology!Learn More





