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 in Dart is an equality relational operator used to evaluate whether two object references represent the same logical value. Unlike languages where == is strictly a primitive operation, in Dart, == is an instance method defined on the base Object class, allowing custom types to define their own structural equality semantics. When the Dart runtime evaluates the expression a == b, it does not immediately invoke the method. Instead, it executes a predefined sequence to safely handle null references:
  1. If a and b are both null, it returns true.
  2. If only one of a or b is null, it returns false.
  3. Otherwise, it invokes the method a.==(b) and returns the resulting boolean.

Default Behavior

By default, all classes inherit the == implementation from Object. This default implementation evaluates strictly for referential equality (identity). It returns true only if both operands point to the exact same instance in memory, making it functionally equivalent to the top-level identical(a, b) function.

Syntax and Signature

The operator is defined as a method with the following signature:
bool operator ==(Object other);
Because the parameter is of type Object, any implementation must perform type checking before accessing properties specific to the subclass.

Overriding the Operator

To implement value equality (where two distinct instances are considered equal if their internal states match), a class must override the == operator. When overriding ==, the Dart language contract strictly dictates that the hashCode getter must also be overridden. If two objects evaluate to true via the == operator, they must produce the exact same integer when their hashCode is accessed. Failure to maintain this contract results in unpredictable behavior when the objects are used in hash-based collections like Set or Map.
class Entity {
  final int id;
  final String value;

  Entity(this.id, this.value);

  @override
  bool operator ==(Object other) {
    // 1. Check for referential equality (performance optimization)
    if (identical(this, other)) return true;

    // 2. Type check and cast
    // 3. Compare internal state
    return other is Entity &&
           other.id == id &&
           other.value == value;
  }

  @override
  int get hashCode => Object.hash(id, value);
}

Key Characteristics

  • Symmetry: a == b should always yield the same result as b == a.
  • Transitivity: If a == b and b == c, then a == c.
  • Reflexivity: a == a must always return true.
  • Non-nullable parameter: The other parameter in the override signature is Object, not Object?, because Dart’s implicit null-checking sequence guarantees that null will never be passed to the method.
Master Dart with Deep Grasping Methodology!Learn More