D
Dart LanguageEasy20 XP3 min read

How should you implement == and hashCode in Dart?

TL;DR: Override both == and hashCode together — they form a contract. Objects that are == must have the same hashCode. Use package:equatable or package:freezed to generate these automatically.

Full Answer

By default, Dart's == checks object identity. For value objects (BLoC states, models), you typically want value equality — two instances with the same fields are equal.

⚠️

Breaking the == / hashCode contract (equal objects with different hashCodes) causes incorrect behavior in HashSets, HashMaps, and BLoC's buildWhen optimization.

Code Examples

dartManual == and hashCode, and using Equatable
Output
true
a
true

Interview Tip

💡

BLoC uses == to determine if a new state should trigger a rebuild. Without proper equality, emitting the 'same' state always triggers a rebuild. Equatable fixes this.

#equality#hashcode#equatable#value-objects