In flutter what is the use of hasCode , equal to operator (== operator)
#flutter
Answer
Overview
text
hashCodetext
==Default Behavior (Reference Equality)
dartclass Point { int x, y; Point(this.x, this.y); } final p1 = Point(1, 2); final p2 = Point(1, 2); print(p1 == p2); // false! Different instances print(p1.hashCode == p2.hashCode); // false! Different hashes print(identical(p1, p2)); // false (different objects in memory)
Overriding == and hashCode
dartclass Point { final int x, y; const Point(this.x, this.y); // Override == for value equality bool operator ==(Object other) { if (identical(this, other)) return true; // Same reference if (other is! Point) return false; // Different type return x == other.x && y == other.y; // Compare values } // Override hashCode to match == int get hashCode => Object.hash(x, y); // Combine field hashes String toString() => 'Point($x, $y)'; } void main() { final p1 = Point(1, 2); final p2 = Point(1, 2); final p3 = Point(3, 4); print(p1 == p2); // true ✅ print(p1 == p3); // false ✅ print({p1, p2}.length); // 1 — Set deduplication works! // Works in Maps too final map = {p1: 'origin'}; print(map[p2]); // 'origin' — p2 equals p1, finds the key }
Rules for == and hashCode
textRULE 1: If a == b, then a.hashCode == b.hashCode (MUST) RULE 2: If a.hashCode == b.hashCode, a == b is NOT guaranteed (hash collision) RULE 3: hashCode should be consistent during object's lifetime RULE 4: Override BOTH together — never just one
Using Equatable (Flutter Best Practice)
dartimport 'package:equatable/equatable.dart'; class User extends Equatable { final int id; final String name; const User({required this.id, required this.name}); List<Object> get props => [id, name]; // Fields for equality } // Works automatically User(id: 1, name: 'Alice') == User(id: 1, name: 'Alice'); // true
Use Cases
| Use Case | Why hashCode + == Matters |
|---|---|
| Set deduplication | text |
| Map keys | text |
| BLoC/Riverpod | Equatable prevents duplicate state rebuilds |
| List.contains() | Searches using == |
| Unit testing | text |
Golden Rule: If you override
, you MUST overridetext==. If two objects are equal (texthashCode), they must have the same hash code — otherwisetexta == bandtextSetwill break.textMap