目录

hash_and_equals

Always override hashCode if overriding ==.

此规则自 Dart 2.0 版本起可用。

_规则集:core , recommended , flutter _

此规则提供 快速修复

详情

#

DO override hashCode if overriding == and prefer overriding == if overriding hashCode.

Every object in Dart has a hashCode. Both the == operator and the hashCode property of objects must be consistent in order for a common hash map implementation to function properly. Thus, when overriding ==, the hashCode should also be overridden to maintain consistency. Similarly, if hashCode is overridden, == should be also.

BAD:

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

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

GOOD:

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 文件中,在 linter > rules 下添加 hash_and_equals

analysis_options.yaml
yaml
linter:
  rules:
    - hash_and_equals