Skip to content

always_remove_listener

v0.4.0WarningFixConfigurableResource Management

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.

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();
}

This rule is in the core preset, so it is on with preset: core, preset: recommended or preset: opinionated.

To turn it off:

many_lints.yaml
rules:
always_remove_listener: false

To keep the rule on but skip certain paths, use per-rule exclude.

Projects with a state abstraction that does not extend Flutter’s State can opt that base class into this rule:

analysis_options.yaml
many_lints:
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