hash_and_equals
Always override hashCode
if overriding ==
.
This rule is available as of Dart 2.0.
Rule sets: core, recommended, flutter
This rule has a quick fix available.
Details
#DO override hashCode
if overriding ==
and prefer overriding ==
if
overriding hashCode
.
Every object in Dart has a hashCode
. Both the ==
operator and the
hashCode
property of objects must be consistent in order for a common hash
map implementation to function properly. Thus, when overriding ==
, the
hashCode
should also be overridden to maintain consistency. Similarly, if
hashCode
is overridden, ==
should be also.
BAD:
class Bad {
final int value;
Bad(this.value);
@override
bool operator ==(Object other) => other is Bad && other.value == value;
}
GOOD:
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;
}
Usage
#To enable the hash_and_equals
rule,
add hash_and_equals
under linter > rules in your
analysis_options.yaml
file:
linter:
rules:
- hash_and_equals
除非另有说明,文档之所提及适用于 Dart 3.5.3 版本,本页面最后更新时间: 2024-08-02。 查看文档源码 或者 报告页面问题。