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