Equality and comparison

suggest change

Dart provides distinct mechanisms for evaluating referential identity (whether two references point to the exact same object in memory) and structural value equality (whether two distinct instances hold identical state).

Understanding how to implement equality, hash codes, and the Comparable interface is critical for correct behavior when working with collections, maps, sets, and state management frameworks.


Identity (identical) vs Equality (==)

  1. identical(a, b): Returns true if and only if a and b reference the exact same memory address.
  2. a == b: Invokes the operator == method defined on a. By default on Object, == defaults to identical(this, other).
void main() {
  final list1 = [1, 2, 3];
  final list2 = [1, 2, 3];
  final list3 = list1;

  print(identical(list1, list2)); // false (different heap allocations)
  print(identical(list1, list3)); // true  (same memory address)
  
  // Lists in Dart inherit Object.== by default (identity comparison):
  print(list1 == list2); // false!
}

Implementing Value Equality and hashCode

To compare custom domain objects by their properties rather than memory addresses, override both operator == and hashCode together:

class User {
  final int id;
  final String email;

  const User({required this.id, required this.email});

  @override
  bool operator ==(Object other) {
    if (identical(this, other)) return true;
    return other is User && other.id == id && other.email == email;
  }

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

void main() {
  // Not `const`: identical const expressions are canonicalized into one object.
  final u1 = User(id: 1, email: 'alice@example.com');
  final u2 = User(id: 1, email: 'alice@example.com');

  print(u1 == u2); // true (Value equality)

  // Sets and Map keys rely on consistent hashCode:
  final userSet = {u1};
  print(userSet.contains(u2)); // true
}

The Hash Code Contract: If a == b, then a.hashCode must equal b.hashCode. If two equal objects produce different hash codes, collections like HashSet and HashMap will fail to locate keys.


Built-In Value Equality with Dart 3 Records

Dart 3 records provide automatic structural equality and hash codes out of the box without boilerplate:

void main() {
  final pointA = (x: 10, y: 20);
  final pointB = (x: 10, y: 20);

  // Records automatically compare values of all fields
  print(pointA == pointB); // true
  print(pointA.hashCode == pointB.hashCode); // true
}

Ordering and Comparison (Comparable<T>)

To support sorting and comparison operators (<, <=, >, >=), implement the Comparable<T> interface:

class PriorityTask implements Comparable<PriorityTask> {
  final String name;
  final int priorityLevel; // 1 = High, 5 = Low

  PriorityTask(this.name, this.priorityLevel);

  @override
  int compareTo(PriorityTask other) {
    // Returns negative if this < other, zero if equal, positive if this > other
    return priorityLevel.compareTo(other.priorityLevel);
  }

  // Operator overloads for clean call sites
  bool operator <(PriorityTask other) => compareTo(other) < 0;
  bool operator >(PriorityTask other) => compareTo(other) > 0;
  bool operator <=(PriorityTask other) => compareTo(other) <= 0;
  bool operator >=(PriorityTask other) => compareTo(other) >= 0;
}

void main() {
  final t1 = PriorityTask('Fix production outage', 1);
  final t2 = PriorityTask('Update documentation', 4);

  print(t1 < t2); // true (higher priority level is smaller number)

  final tasks = [t2, t1];
  tasks.sort(); // Uses compareTo automatically
  print(tasks.map((t) => t.name).toList());
  // [Fix production outage, Update documentation]
}

Deep Collection Equality (package:collection)

By default, Dart collections (List, Set, Map) use identity comparison (identical). To compare the contents of lists or nested maps, use package:collection:

import 'package:collection/collection.dart';

void main() {
  final a = [1, 2, [3, 4]];
  final b = [1, 2, [3, 4]];

  // Standard equality checks references:
  print(a == b); // false

  // Shallow list equality:
  print(const ListEquality().equals([1, 2], [1, 2])); // true

  // Deep collection equality (handles nested lists and maps):
  final deepEq = const DeepCollectionEquality();
  print(deepEq.equals(a, b)); // true
}

Simplifying Equality with package:equatable

In Flutter and Dart applications with many data classes, package:equatable eliminates repetitive == and hashCode implementations:

import 'package:equatable/equatable.dart';

class Product extends Equatable {
  final String sku;
  final double price;

  const Product({required this.sku, required this.price});

  // Declare properties to include in equality and hashing
  @override
  List<Object?> get props => [sku, price];
}

void main() {
  final p1 = Product(sku: 'A100', price: 29.99);
  final p2 = Product(sku: 'A100', price: 29.99);

  print(p1 == p2); // true
}

Best Practices

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents