==) evaluates the equivalence of two objects. By default, it determines if two variables reference the same object in memory (identity equality), but it can be overridden to establish structural equality based on object state.
Semantics and Dispatch
In Dart, the expressionx == y is syntactic sugar for a method call with built-in null safety handling. The runtime executes the following logic:
- Identity Check: If
xandyare the same instance (reference the same memory location) or both arenull, returntrue. - Null Check: If only one operand is
null, returnfalse. - Method Invocation: Return the result of
x.operator==(y).
operator== inside a class does not need to check if the argument is null.
Default Implementation
The base implementation in theObject class relies solely on identity. It uses the identical() function to check if the pointers are equal.
Overriding for Structural Equality
To compare objects based on their internal values (fields) rather than their memory address, a class must override the== operator.
A valid override must adhere to the mathematical properties of an equivalence relation:
- Reflexive:
a == ais always true. - Symmetric:
a == bimpliesb == a. - Transitive:
a == bandb == cimpliesa == c.
Syntax
The HashCode Contract
Dart enforces a contract betweenoperator == and get hashCode. If two objects are considered equal according to operator ==, they must have the same hashCode.
Failure to override hashCode when overriding == will result in undefined behavior when the objects are used in hash-based collections (e.g., Set, Map).
Type Safety
The parameter type foroperator == is Object, not the specific class type. This allows comparison between objects of different types without throwing runtime errors.
In Dart 2.12 and later (Null Safety), the signature is bool operator ==(Object other). The parameter is non-nullable because the runtime guarantees that null is never passed to this method (handled in the dispatch step).
Dart allows the use of covariant to tighten the parameter type, though this is generally discouraged for operator == as it violates the standard contract where comparison against an unrelated type should return false rather than throw a TypeError.
Master Dart with Deep Grasping Methodology!Learn More





