跳到主要內容

hash_and_equals

穩定
核心
提供修正

如果覆寫 ==,請務必覆寫 hashCode

詳細資訊

#

務必在覆寫 == 時覆寫 hashCode,並且在覆寫 hashCode 時優先覆寫 ==

Dart 中的每個物件都有 hashCode。物件的 == 運算子和 hashCode 屬性必須一致,才能使常見的雜湊表實作正常運作。因此,當覆寫 == 時,也應覆寫 hashCode 以保持一致性。同樣地,如果覆寫了 hashCode,也應覆寫 ==

不良範例

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

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

良好範例

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

如果您改為使用 YAML map 語法來設定 linter 規則,請在 linter > rules 下新增 hash_and_equals: true

analysis_options.yaml
yaml
linter:
  rules:
    hash_and_equals: true