跳到主內容

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