dispose_owned_resources
Reports a resource that a Flutter State creates and never releases. Release it in dispose.
- Tier
- blocking
- Scope
- Flutter
- Fix
- add the release call to
dispose
What it reports
Section titled “What it reports”A field of a State that holds a resource the State created, and that dispose never releases. The violation is at the name of the field.
| Type | From | Released by |
|---|---|---|
StreamSubscription |
dart:async |
cancel |
Timer |
dart:async |
cancel |
StreamController |
dart:async |
close |
ChangeNotifier |
Flutter | dispose |
AnimationController |
Flutter | dispose |
Ticker |
Flutter | dispose |
Subtypes count too: TextEditingController, ScrollController, PageController, TabController, FocusNode, ValueNotifier and your own ChangeNotifier classes are change notifiers. The rule parameter extra_disposables adds types of your own.
- Created by the
State: a constructor call such asTextEditingController()orTimer.periodic(…), orstream.listen(…), assigned to the field anywhere in the class.widget.controller ?? TextEditingController()counts too: the controller it creates has to be released. - Released:
dispose, or a method of the class it calls, calls a release method on the field (dispose,cancel,close, a name with one of them as a word such asdisposeSafely, or the methodextra_disposablesnames), or hands the field on to a call. - A
Statethat declares nodisposereleases nothing.
It does not report a resource handed in from outside (widget.controller), one that a function or a static method gives (PrimaryScrollController.of(context)), or one that is not a field, such as a local variable.
Controllers, focus nodes, subscriptions and timers live outside the widget tree: when the State is removed, the timer keeps firing, the subscription keeps delivering events and the animation controller keeps its ticker. Each keeps the State in memory, and a callback that then calls setState throws. Forgetting the release is one of the most frequent defects in generated Flutter code, because the line that releases a resource changes nothing you can see.
Example
Section titled “Example”class _SearchState extends State<Search> { final _controller = TextEditingController(); StreamSubscription<Result>? _results;
@override void initState() { super.initState(); _results = widget.results.listen(_show); }}class _SearchState extends State<Search> { final _controller = TextEditingController(); StreamSubscription<Result>? _results;
@override void initState() { super.initState(); _results = widget.results.listen(_show); }
@override void dispose() { _results?.cancel(); _controller.dispose(); super.dispose(); }}A controller that is the widget’s when the widget has one is released only when the State made it:
late final _controller = widget.controller ?? TextEditingController();
@overridevoid dispose() { if (widget.controller == null) _controller.dispose(); super.dispose();}The fix, Release the State’s resources in ‘dispose’, is offered in the editor at each violation where it is available, and assay fix applies it across the project in one run. The violation’s line in the gate’s message carries [fix available].
The fix only adds code. It writes the release call of every resource of the State that the rule reports, directly before super.dispose(), and adds a dispose where there is none. A release that returns a future is handed to unawaited: unawaited(_results?.cancel());.
Rule parameters
Section titled “Rule parameters”Set under the assay: key of the project’s root analysis_options.yaml.
| Rule parameter | Default | Effect |
|---|---|---|
extra_disposables |
{} |
A map from the name of a type to the name of the method that releases it, for resource types of the project and of its packages. A field whose type is the named type or a subtype of it is then a resource, and a call of the named method releases it. |
enabled |
true |
false switches the rule off for the whole project. |
exclude |
[] |
Path globs where the rule is silent. |
assay: rules: dispose_owned_resources: extra_disposables: VideoPlayerController: dispose DatabaseConnection: closeSuppressing it
Section titled “Suppressing it”Write why on the line directly above the suppression:
// The session bag cancels every subscription that is added to it.// ignore: assay/dispose_owned_resources// ignore_for_file: assay/dispose_owned_resources silences it in a whole file, and // ignore: dispose_owned_resources without the prefix works too. See Suppressions.
Details
Section titled “Details”All cases
What it reports, in full
Section titled “What it reports, in full”The field is a resource. It is an instance field of a class that extends State, and its type has to be released, each with the method its own class gives (the table above). A type counts by itself and by its supertypes. TextEditingController, ScrollController, PageController, TabController, FocusNode and ValueNotifier are change notifiers, and so is a class of the project that extends or mixes in ChangeNotifier. A nullable or late field counts like any other. The rule parameter extra_disposables adds types of your own.
The State creates it. Somewhere in the class, a resource created right there is assigned to the field: in the field’s declaration, in a constructor’s initializer, or in an assignment in any method. Created right there means:
- a constructor call,
TextEditingController(),Timer.periodic(…),AnimationController(vsync: this), also as a dot shorthand:final TextEditingController controller = .new();; - the
listencall that gives a subscription,stream.listen(…), also with a cascade on it; - either of these as one side of
??or of a conditional expression.widget.controller ?? TextEditingController()creates a controller when none was handed in, and that one has to be released.
The State never releases it. Neither dispose nor a method of the class that dispose calls on the state itself, directly or through another one, does one of these with the field:
- calls a method on it that releases it:
controller.dispose(),timer?.cancel(),subscription!.cancel(),this.focusNode.dispose(),controller..removeListener(changed)..dispose(); - calls such a method on its
sink:changes.sink.close()closes the stream controller; - hands it on: as an argument of a call (
release(controller)), as an element of a list or a set (for (final each in [first, second]) each.dispose()), as the value a local variable starts with (final running = timer;), as the value an if-case matches, or as the release method torn off (addTearDown(controller.dispose)).
A State that declares no dispose releases nothing.
It does not report:
- a resource that
disposereleases, itself or through a method it calls; - a resource handed in from outside and never created by the
State:late final controller = widget.controller;, a field the constructor takes as an argument, a field a method sets from its argument; - a resource that a call of a function or a static method gives, such as
makeController()orPrimaryScrollController.of(context): whether theStateowns it cannot be read from the call; - a resource that is not a field of its own: a local variable, a timer started and not kept, the elements of a list of controllers, a static field;
- a field of a class that is no
State; - anything in a package that does not use Flutter.
The rule looks at dispose and at what dispose calls, not at the whole class. A timer that is cancelled only before it is started again still runs when the State is gone:
void _restart() { _timer?.cancel(); _timer = Timer(const Duration(seconds: 1), _tick);}The framework cannot release resources for the State, because it does not know which ones the State owns: dispose is where the State says so.
It also reports a resource that is released where dispose does not reach through the class’s own methods: in deactivate, in a method of a superclass or a mixin, in a subclass, in a callback registered elsewhere, or through a getter. The same holds for a resource that another object releases outside dispose, such as a subscription added to a collection that dispose cancels as a whole, and for an object that a factory constructor gives without creating it, such as a shared instance. Keep such a field with a justified suppression. A release through a method whose name does not say so, such as an extension method tearDown(), counts once extra_disposables names it for the type.
A method that releases it
Section titled “A method that releases it”A call releases the field when it calls:
- the method the table gives for its type, or the one
extra_disposablesnames; - any method whose name says release:
dispose,cancelorclose, or a name with one of the three as a word of its own, such asdisposeSafely,safeDispose,cancelAllorcloseQuietly. A word that only starts like one, such asisClosed,markDisposedorcancelled, does not count.
The second is read from the name alone, whatever method it stands for: the type’s own, one a subtype adds, or an extension method of the project that wraps the release, perhaps in another file the rule cannot read. A blocking rule that reported controller.disposeSafely() in dispose would hold up code that is right, so a call on the field in dispose of something named a release is taken as the release.
How the fix decides
Section titled “How the fix decides”A result says when a fix is available. The fix only adds code; it changes nothing that is there.
- The call is the release method of the field’s type, from the table above or from
extra_disposables:_controller.dispose();,_timer.cancel();,_connection.shutDown();. A nullable field gets?.:_events?.cancel();. A release method that returns a future, such ascancelof a subscription andcloseof a stream controller, has its future handed tounawaited, so that the SDK lintdiscarded_futures, on inrecommendedandstrict, does not report the line:unawaited(_events?.cancel());. Whereunawaitedis not visible, the fix importsdart:async, or addsunawaitedto theshowof the import that is there. - One
disposefor the wholeState. The fix of any violation writes the release calls of every resource of thatStatethat the rule reports, no suppression hides and the fix can release, in the order of their fields. The editor releases them all at the first violation, andassay fixwrites them once and counts every violation as fixed. - Where
disposeexists, the calls go directly beforesuper.dispose(), each on a line of its own. Adisposethat does not callsuper.dispose()(the SDK reports that asmust_call_super) gets them at its end, before a finalreturn; the fix does not add the missing call, which is for you to decide. - Where there is none, the fix adds
@override void dispose()that makes the calls and then callssuper.dispose(). It goes after the last life-cycle method beforedisposethat theStatedeclares (initState,didChangeDependencies,didUpdateWidget,reassemble,activate,deactivate), or else after its last field or constructor, formatted as the formatter would leave it.
Applied to the violating example above, the fix writes:
class _SearchState extends State<Search> { final _controller = TextEditingController(); StreamSubscription<Result>? _results;
@override void initState() { super.initState(); _results = widget.results.listen(_show); }
@override void dispose() { _controller.dispose(); unawaited(_results?.cancel()); super.dispose(); }}A dispose that is there keeps what it has:
@overridevoid dispose() { _controller.removeListener(_changed); _controller.dispose(); super.dispose();}Where the release cannot be added mechanically, the violation says that no fix is available. Once the fix has run, the rule reports nothing for the field.
When the fix is not available
Section titled “When the fix is not available”- The
Statemay not own what the field holds whendisposeruns: the field takes the widget’s controller when there is one (widget.controller ?? TextEditingController(), or a conditional expression with such a branch), or the class assigns it in more than one place, apart from assigningnull. - The field is
latewith an initializer: a release indisposewould create the resource there, where nothing read the field before.late final _events = widget.events.listen(…)would start listening indispose. disposemay read alatefield before it is assigned: the field has no initializer, andinitStatedoes not assign it unconditionally, in a statement directly in its body before anything that can return.- The release method is not certain: the type has more than one by the table and
extra_disposables, or no instance method of that name callable without arguments (anextra_disposablesentry that names an extension method, or no method of the type). disposemay already release the field in a form the rule does not follow: an extension method called on the field, or the field read under a cast.- Another class may release the resources of the
State: a supertype or mixin from outside the Flutter framework declares adispose, or a class of the same file extends theState. Flutter’s mixins, such asSingleTickerProviderStateMixin, release nothing of theStateand do not count. - The class releases the field where
disposedoes not reach, such as indeactivate, in a callback thatinitStateregisters, or in a method thatdisposehands on by its name (scheduleMicrotask(_release)). - The class reads the field under another name: it returns it, from a getter (
TextEditingController get _current => _controller;) or any function, or gives it to a variable, another field, a record or a map, also as a branch of a conditional expression or of??. - The release returns a future and
unawaitedcannot be made callable by adding code alone: in a part whose library does not make it visible, in a file that importsdart:asyncwithhide unawaited, or whereunawaitednames another function. The other resources of the sameStateare released all the same. disposeis an expression, asynchronous, a generator, or has no statement and nosuper.dispose()call; a member nameddisposeis no method; a name declared indisposehides the field; ordisposeassigns the field.
Rule parameter fine print
Section titled “Rule parameter fine print”A type in extra_disposables is named by its name alone, without its library or type arguments. A name that is also in the table above gets the method named here instead of the table’s. A value that is not a map from strings to strings is a configuration error.