跳到主要內容

hash_and_equals

缺少對 '{0}' 的對應重寫。

描述

#

當類或混入重寫了 == 的定義但未重寫 hashCode 的定義,或者相反地重寫了 hashCode 的定義但未重寫 == 的定義時,分析器會產生此診斷。

物件上的 == 運算子和 hashCode 屬性必須保持一致,以確保常見的雜湊對映實現能正常工作。因此,在重寫其中任一方法時,兩者都應被重寫。

示例

#

以下程式碼會產生此診斷,因為類 C 重寫了 == 運算子但未重寫 getter hashCode

dart
class C {
  final int value;

  C(this.value);

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

常見修復方法

#

如果您需要重寫其中一個成員,請新增對另一個成員的重寫。

dart
class C {
  final int value;

  C(this.value);

  @override
  bool operator ==(Object other) =>
      other is C &&
      other.runtimeType == runtimeType &&
      other.value == value;

  @override
  int get hashCode => value.hashCode;
}

如果您不需要重寫任一成員,請移除不必要的重寫。

dart
class C {
  final int value;

  C(this.value);
}