跳到主要內容

avoid_equals_and_hash_code_on_mutable_classes

穩定

避免在未標記 @immutable 的類別上多載運算子 == 和 hashCode。

詳細資訊

#

出自Effective Dart

避免在未標記 @immutable 的類別上多載運算子 == 和 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