1

我正在看这个例子

@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;
}

hashCode 与此有什么关系?它是干什么用的?(我已经缩短了代码,因为我收到了我发布的大多数代码的 stackoverflow 错误)

谢谢

4

1 回答 1

1

您在这里看到这一点,因为该类覆盖了==运算符。

hashCode当您覆盖运算符时,应始终覆盖==。在使用HashMaphashCode之类的 Hash 类或将列表转换为集合(这也是散列)时,会使用任何对象的 。

更多信息:

  1. https://medium.com/@ayushpguptaapg/demystifying-and-hashcode-in-dart-2f328d1ab1bc
  2. https://www.geeksforgeeks.org/override-equalsobject-hashcode-method/ 以 Java 作为编程语言进行解释,但应该适用于 dart。
于 2020-11-19T18:55:55.107 回答