1

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

user3808307
  • 2,270
  • 9
  • 45
  • 99

1 Answers1

2

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:

  1. https://medium.com/@ayushpguptaapg/demystifying-and-hashcode-in-dart-2f328d1ab1bc
  2. https://www.geeksforgeeks.org/override-equalsobject-hashcode-method/ explains with Java as the programming language but should hold good for dart.
Prathik
  • 474
  • 3
  • 13