跳到主要内容

avoid_equals_and_hash_code_on_mutable_classes

稳定

避免在未标记为 @immutable 的类上重载 operator == 和 hashCode。

详情

#

来自 Effective Dart

避免在未标记为 @immutable 的类上重载 operator == 和 hashCode。

如果一个类不是不可变的,当在集合中使用时,重载 operator ==hashCode 可能会导致不可预测和不良的行为。

错误示例

dart
class B {
  String key;
  const B(this.key);
  @override
  operator ==(other) => other is B && other.key == key;
  @override
  int get hashCode => key.hashCode;
}

正确示例

dart
@immutable
class A {
  final String key;
  const A(this.key);
  @override
  operator ==(other) => other is A && other.key == key;
  @override
  int get hashCode => key.hashCode;
}

注意:lint 检查 @immutable 注释的使用,即使类在其他方面不是可变的,也会触发。

错误示例

dart
class C {
  final String key;
  const C(this.key);
  @override
  operator ==(other) => other is C && other.key == key;
  @override
  int get hashCode => key.hashCode;
}

启用

#

要启用 avoid_equals_and_hash_code_on_mutable_classes 规则,请在您的 analysis_options.yaml 文件中的 linter > rules 下添加 avoid_equals_and_hash_code_on_mutable_classes

analysis_options.yaml
yaml
linter:
  rules:
    - avoid_equals_and_hash_code_on_mutable_classes

如果您改为使用 YAML 映射语法来配置 linter 规则,请在 linter > rules 下添加 avoid_equals_and_hash_code_on_mutable_classes: true

analysis_options.yaml
yaml
linter:
  rules:
    avoid_equals_and_hash_code_on_mutable_classes: true