Issue
I am looking at this example
@immutable
class UserState {
final bool isLoading;
final LoginResponse user;
UserState({
@required this.isLoading,
@required this.user,
});
factory UserState.initial() {
return new UserState(isLoading: false, user: null);
}
UserState copyWith({bool isLoading, LoginResponse user}) {
return new UserState(
isLoading: isLoading ?? this.isLoading, user: user ?? this.user);
}
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is UserState &&
runtimeType == other.runtimeType &&
isLoading == other.isLoading &&
user == other.user;
@override
int get hashCode => isLoading.hashCode ^ user.hashCode;
}
What does a hashCode have to do with this? What is it used for? (I have shortened the code because I get a stackoverflow error that I am posting mostrly code)
Thank you
Solution
You’re seeing this here as the class overrides the ==
operator.
One should always override hashCode
when you override the ==
operator.
The hashCode
of any object is used while working with Hash classes like HashMap or when you’re converting a list to a set, which is also hashing.
more info:
- https://medium.com/@ayushpguptaapg/demystifying-and-hashcode-in-dart-2f328d1ab1bc
- https://www.geeksforgeeks.org/override-equalsobject-hashcode-method/
explains with Java as the programming language but should hold good for dart.
Answered By – Prathik
Answer Checked By – Senaida (FlutterFixes Volunteer)