Question #108EasyDart Basics

In flutter what is the use of hasCode , equal to operator (== operator)

#flutter

Answer

Overview

text
hashCode
and the
text
==
operator in Dart are used to determine equality between objects. By default, two different object instances are never equal — you must override these to enable value-based equality.


Default Behavior (Reference Equality)

dart
class 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

dart
class 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

text
RULE 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)

dart
import '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 CaseWhy hashCode + == Matters
Set deduplication
text
{user1, user2}
— duplicates removed by hashCode/==
Map keys
text
map[user]
— looks up by hash then ==
BLoC/RiverpodEquatable prevents duplicate state rebuilds
List.contains()Searches using ==
Unit testing
text
expect(result, expected)
uses ==

Golden Rule: If you override

text
==
, you MUST override
text
hashCode
. If two objects are equal (
text
a == b
), they must have the same hash code — otherwise
text
Set
and
text
Map
will break.