prefer_overriding_parent_equality
v0.4.0 Warning Fix Collection & Type
When a parent class overrides == and hashCode, child classes that add new fields should also override both operators. Otherwise, the inherited equality ignores the child’s fields, meaning two child instances with different field values may be considered equal.
Why use this rule
Section titled “Why use this rule”Inheriting a parent’s == without overriding it in the child means the child’s own fields are excluded from equality checks. This causes silent bugs in collections, state comparison, and testing where logically different objects appear identical.
See also: Dart operator == and hashCode | Dart lint: hash_and_equals
class Parent { final int id; Parent(this.id);
@override int get hashCode => id.hashCode;
@override bool operator ==(Object other) => other is Parent && id == other.id;}
// Missing both == and hashCode overridesclass Child extends Parent { final String name; Child(this.name, int id) : super(id);}
// Missing hashCode overrideclass ChildMissingHashCode extends Parent { final String name; ChildMissingHashCode(this.name, int id) : super(id);
@override bool operator ==(Object other) => other is ChildMissingHashCode && name == other.name && id == other.id;}
// Missing == overrideclass ChildMissingEquals extends Parent { final String name; ChildMissingEquals(this.name, int id) : super(id);
@override int get hashCode => Object.hash(id, name);}// Child overrides both == and hashCodeclass GoodChild extends Parent { final String name; GoodChild(this.name, int id) : super(id);
@override int get hashCode => Object.hash(id, name);
@override bool operator ==(Object other) => other is GoodChild && id == other.id && name == other.name;}
// Abstract class is not flaggedabstract class AbstractChild extends Parent { final String label; AbstractChild(this.label, int id) : super(id);}
// Parent does not override equality — no warningclass SimpleParent { final int x; SimpleParent(this.x);}
class SimpleChild extends SimpleParent { final int y; SimpleChild(this.y, int x) : super(x);}Configuration
Section titled “Configuration”This rule is in the opinionated preset, so it is on with
preset: opinionated, or by name:
rules: prefer_overriding_parent_equality: trueTo turn it off again:
rules: prefer_overriding_parent_equality: falseTo keep the rule on but skip certain paths, use per-rule exclude.
Related rules
Section titled “Related rules”avoid_collection_equality_checks— Avoid comparing collections with == or != as it checks reference equality, not contents.list_all_equatable_fields— Ensure all fields are listed in Equatable props.prefer_equatable_mixin— Prefer using EquatableMixin instead of extending Equatable.avoid_accessing_collections_by_constant_index— Avoid accessing a collection by a constant index inside a loop.