DartIntermediate 2 min read

Dart equality and hashCode: use model IDs as set keys

Implement consistent value equality and keep hash-relevant fields immutable.

On this page

A set decides whether two values represent the same member through equality and hashing. If a domain ID is represented by an object, define that contract consistently. The object should not change its hash-relevant state after insertion.

Worked example

Language requirement: Dart 3.0 or later. This complete example uses browser-supported libraries.

main.dart
class ProductId {
  const ProductId(this.value);
  final String value;
  @override
  bool operator ==(Object other) => other is ProductId && other.value == value;
  @override
  int get hashCode => value.hashCode;
}

void main() {
  final first = ProductId('CABLE-1');
  final second = ProductId('CABLE-1');
  final ids = {first, second};
  print(ids.length);
  print(ids.contains(const ProductId('CABLE-1')));
}

Follow the data and control flow

Two IDs with the same value compare equal and therefore must have equal hash codes. The set contains one logical member. A final value avoids changing the lookup key after insertion, which could make membership operations behave unexpectedly.

Equality should be reflexive, symmetric and transitive. When several fields participate, combine them consistently with an appropriate helper such as Object.hash. Do not add a display label to equality unless changing that label genuinely changes the domain value.

A mistake to avoid

Overriding equality without a matching hashCode breaks hashed collection expectations. Also avoid confusing object identity with value equality: identical answers a different question. A list field’s default equality is not automatically a deep comparison of its contents.

Practice and verification

Create two separate non-const instances with the same ID and verify set behavior. Add a namespace field and update both equality and hashing. Explain why a database row with mutable attributes may still use a stable immutable ID for lookup.

How this topic connects

Apply it next

Lesson progressMark complete after checking the example and exercise.

Find your next idea

Search lessons, code examples and projects.

Type a few words to start exploring.