avoid_equals_and_hash_code_on_mutable_classes
避免在未标记为 @immutable
的类上重载 operator == 和 hashCode。
详情
#避免在未标记为 @immutable
的类上重载 operator == 和 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