Skip to content

listener_never_removed

Reports an addListener in a State, on an object the state does not own, whose listener the class never removes. Remove it in dispose with the same callback, kept in a method or a field rather than written as a function literal.

Tier
advisory
Scope
Flutter
Lowest preset
recommended
Fix
none

An addListener call on a Flutter Listenable, in a class that extends State, whose listener the class never removes, on an object the state does not own. The target is a chain of names, such as widget.controller or Settings.instance. The violation is on the call.

The listener counts as removed when a removeListener call in the class takes the same callback, named the same way, on the same target. A target that is not such a chain counts too, such as the oldWidget of didUpdateWidget or a parameter of a helper.

A function literal can never be removed, so it is reported on a target the state does not own.

It does not report a target the state owns: a field to which the class assigns an object it creates, or a field it releases. Such an object goes with the state, and dispose_owned_resources reports one that is never released.

The rule is silent in a package that does not use Flutter.

The listened object outlives the state and goes on calling it after it is disposed. A setState on a disposed state throws, and the listener keeps the state alive.

Violating
@override
void initState() {
super.initState();
widget.controller.addListener(_changed);
}
Corrected
@override
void initState() {
super.initState();
widget.controller.addListener(_changed);
}
@override
void dispose() {
widget.controller.removeListener(_changed);
super.dispose();
}

Set under the assay: key of the project’s root analysis_options.yaml.

Rule parameter Default Effect
enabled true false switches the rule off for the whole project.
exclude [] Path globs where the rule is silent.

Write why on the line directly above the suppression:

// Why this place is fine.
// ignore: listener_never_removed

// ignore_for_file: assay/listener_never_removed silences it in a whole file, and // ignore: assay/listener_never_removed with the prefix works too. See Suppressions.