目录

avoid_equals_and_hash_code_on_mutable_classes

Avoid overloading operator == and hashCode on classes not marked @immutable.

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

详情

#

From Effective Dart:

AVOID overloading operator == and hashCode on classes not marked @immutable.

If a class is not immutable, overloading operator == and hashCode can lead to unpredictable and undesirable behavior when used in collections.

BAD:

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

GOOD:

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

NOTE: The lint checks the use of the @immutable annotation, and will trigger even if the class is otherwise not mutable. Thus:

BAD:

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