Skip to main content
The inequality operator (!=) is a relational operator that evaluates the distinction between two objects. It returns a bool value of true if the operands are not equal and false if they are equivalent.

Syntax

bool result = leftOperand != rightOperand;

Operational Semantics

In Dart, the != operator is syntactic sugar for the negation of the equality operator (==). It cannot be explicitly overridden in a class definition. Its behavior is strictly defined as:
!(leftOperand == rightOperand)
Because != relies entirely on the implementation of == on the left-hand operand, the definition of “inequality” depends on whether the object performs referential equality or value equality.

1. Referential Inequality (Default)

By default, classes inherit the == implementation from Object, which compares memory references (identity). The != operator returns true if the operands exist at different memory addresses, even if their internal state is identical.
class Point {
  final int x, y;
  Point(this.x, this.y);
}

void main() {
  var a = Point(1, 1);
  var b = Point(1, 1);
  var c = a;

  // Returns true: 'a' and 'b' are distinct instances in memory
  print(a != b);

  // Returns false: 'a' and 'c' reference the same instance
  print(a != c);
}

2. Value Inequality

If a class overrides the == operator (and the hashCode getter), the != operator evaluates inequality based on the logical content of the objects.
class Vector {
  final int x;
  Vector(this.x);

  @override
  bool operator ==(Object other) =>
      other is Vector && other.x == x;

  @override
  int get hashCode => x.hashCode;
}

void main() {
  var v1 = Vector(10);
  var v2 = Vector(10);

  // Returns false: The overridden == returns true, so != returns false
  print(v1 != v2);
}

Null Handling

The != operator adheres to standard null safety rules regarding identity:
  • Comparing any non-null object to null returns true.
  • Comparing null to null returns false.
int? x = 5;
print(x != null); // true
print(null != null); // false

Static Analysis and Type Safety

The Dart analyzer performs static checks on equality expressions. If the operands are of unrelated types (types that are disjoint and cannot possibly be equal), the analyzer issues a warning. Since the underlying == check is guaranteed to return false for unrelated types, the != operation is guaranteed to return true.
int a = 5;
String b = "5";

// Warning: Equality operator '==' invocation with references of unrelated types.
// Result: true
print(a != b);
Master Dart with Deep Grasping Methodology!Learn More