Middle
How to override the comparison operation for objects in Flutter?
sobes.tech AI
Answer from AI
To override the comparison operator == and hashCode, you need to implement them in the class. The equatable package is often used for this purpose.
import 'package:equatable/equatable.dart';
class MyObject extends Equatable {
final int id;
final String name;
const MyObject(this.id, this.name);
@override
List<Object?> get props => [id, name];
}
Without equatable, the implementation would look like this:
class MyObject {
final int id;
final String name;
const MyObject(this.id, this.name);
@override
bool operator ==(Object other) {
if (identical(this, other)) return true;
return other is MyObject &&
other.id == id &&
other.name == name;
}
@override
int get hashCode => id.hashCode ^ name.hashCode;
}
When overriding ==, it is always necessary to override hashCode as well, to maintain the contract between them: if two objects are equal according to ==, their hash codes must be equal. The reverse is not necessarily true.
Usage:
final obj1 = MyObject(1, 'Test');
final obj2 = MyObject(1, 'Test');
final obj3 = MyObject(2, 'Other');
print(obj1 == obj2); // Output: true
print(obj1 == obj3); // Output: false