always_remove_listener
Flags addListener() calls in State lifecycle methods (initState, didUpdateWidget, didChangeDependencies) that do not have a matching removeListener() call in dispose(). Missing removal causes memory leaks when the Listenable outlives the widget.
Why use this rule
Section titled “Why use this rule”Every addListener() on a ChangeNotifier, ValueNotifier, or AnimationController creates a strong reference to the callback. If the listener is not removed in dispose(), the callback (and everything it captures) stays in memory even after the widget is unmounted. This rule ensures every add has a matching remove with the same target and callback.
See also: ChangeNotifier | removeListener | Dart lint: cancel_subscriptions
class _BadState extends State<BadWidget> { final ValueNotifier<int> _counter = ValueNotifier(0);
@override void initState() { super.initState(); _counter.addListener(_onChanged); // No matching removeListener }
void _onChanged() => setState(() {});
@override Widget build(BuildContext context) => const SizedBox();}class _GoodState extends State<GoodWidget> { final ValueNotifier<int> _counter = ValueNotifier(0);
@override void initState() { super.initState(); _counter.addListener(_onChanged); }
@override void dispose() { _counter.removeListener(_onChanged); super.dispose(); }
void _onChanged() => setState(() {});
@override Widget build(BuildContext context) => const SizedBox();}Turning this rule off
Section titled “Turning this rule off”This rule is in the core preset, so it is on with preset: core,
preset: recommended or preset: opinionated.
To turn it off:
rules: always_remove_listener: falseTo keep the rule on but skip certain paths, use per-rule exclude.
Options
Section titled “Options”Projects with a state abstraction that does not extend Flutter’s State can
opt that base class into this rule:
many_lints: rules: always_remove_listener: state_base_classes: [AppState]rules: always_remove_listener: state_base_classes: [AppState]| Option | Type | Default | Description |
|---|---|---|---|
state_base_classes |
list of strings | [] |
Additional non-State base classes whose subclasses should be treated as state classes |
Related rules
Section titled “Related rules”avoid_unremovable_callbacks_in_listeners— Don’t pass an inline closure to addListener.dispose_fields— Ensure State fields with disposal methods are cleaned up in dispose().dispose_provided_instances— Ensure disposable instances in Riverpod providers are cleaned up with ref.onDispose.avoid_late_final_reassignment— Flag alate finalfield assigned twice on one path.