跳到主要内容

hash_and_equals

稳定
核心
有可用修复

如果覆盖了 ==,则始终覆盖 hashCode

详情

#

务必 在覆盖 == 时覆盖 hashCode,并在覆盖 hashCode 时优先覆盖 ==

Dart 中的每个对象都有一个 hashCode。为了使常见的哈希表实现正常工作,对象的 == 运算符和 hashCode 属性必须保持一致。因此,在覆盖 == 时,也应覆盖 hashCode 以保持一致。同样,如果覆盖了 hashCode,也应覆盖 ==

错误示例

dart
class Bad {
  final int value;
  Bad(this.value);

  @override
  bool operator ==(Object other) => other is Bad && other.value == value;
}

正确示例

dart
class Better {
  final int value;
  Better(this.value);

  @override
  bool operator ==(Object other) =>
      other is Better &&
      other.runtimeType == runtimeType &&
      other.value == value;

  @override
  int get hashCode => value.hashCode;
}

启用

#

要启用 hash_and_equals 规则,请在您的 analysis_options.yaml 文件中将 hash_and_equals 添加到 linter > rules 下方。

analysis_options.yaml
yaml
linter:
  rules:
    - hash_and_equals

如果您改用 YAML map 语法配置 linter 规则,请在 linter > rules 下添加 hash_and_equals: true

analysis_options.yaml
yaml
linter:
  rules:
    hash_and_equals: true