avoid_ equals_ and_ hash_ code_ on_ mutable_ classes
Avoid overloading operator == and hashCode on classes not marked @immutable
.
Details
#From Effective Dart:
AVOID overloading operator == and hashCode on classes not marked @immutable
.
If a class is not immutable, overloading operator ==
and hashCode
can lead to unpredictable and undesirable behavior when used in collections.
BAD:
class B { String key; const B(this.key); @override operator ==(other) => other is B && other.key == key; @override int get hashCode => key.hashCode; }
GOOD:
@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; }
NOTE: The lint checks the use of the @immutable
annotation, and will trigger even if the class is otherwise not mutable. Thus:
BAD:
class C { final String key; const C(this.key); @override operator ==(other) => other is C && other.key == key; @override int get hashCode => key.hashCode; }
Enable
# To enable the avoid_equals_and_hash_code_on_mutable_classes
rule, add avoid_equals_and_hash_code_on_mutable_classes
under linter > rules in your analysis_options.yaml
file:
linter: rules: - avoid_equals_and_hash_code_on_mutable_classes
If you're instead using the YAML map syntax to configure linter rules, add avoid_equals_and_hash_code_on_mutable_classes: true
under linter > rules:
linter: rules: avoid_equals_and_hash_code_on_mutable_classes: true
Unless stated otherwise, the documentation on this site reflects Dart 3.9.2. Report an issue.