Skip to content

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

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 as TextEditingController() or Timer.periodic(…), or stream.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 as disposeSafely, or the method extra_disposables names), or hands the field on to a call.
  • A State that declares no dispose releases 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.

Violating
class _SearchState extends State<Search> {
final _controller = TextEditingController();
StreamSubscription<Result>? _results;
@override
void initState() {
super.initState();
_results = widget.results.listen(_show);
}
}
Corrected
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();
@override
void 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());.

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: close

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.

All cases

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 listen call 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 dispose releases, 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() or PrimaryScrollController.of(context): whether the State owns 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 call releases the field when it calls:

  • the method the table gives for its type, or the one extra_disposables names;
  • any method whose name says release: dispose, cancel or close, or a name with one of the three as a word of its own, such as disposeSafely, safeDispose, cancelAll or closeQuietly. A word that only starts like one, such as isClosed, markDisposed or cancelled, 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.

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 as cancel of a subscription and close of a stream controller, has its future handed to unawaited, so that the SDK lint discarded_futures, on in recommended and strict, does not report the line: unawaited(_events?.cancel());. Where unawaited is not visible, the fix imports dart:async, or adds unawaited to the show of the import that is there.
  • One dispose for the whole State. The fix of any violation writes the release calls of every resource of that State that 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, and assay fix writes them once and counts every violation as fixed.
  • Where dispose exists, the calls go directly before super.dispose(), each on a line of its own. A dispose that does not call super.dispose() (the SDK reports that as must_call_super) gets them at its end, before a final return; 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 calls super.dispose(). It goes after the last life-cycle method before dispose that the State declares (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:

@override
void 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.

  • The State may not own what the field holds when dispose runs: 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 assigning null.
  • The field is late with an initializer: a release in dispose would create the resource there, where nothing read the field before. late final _events = widget.events.listen(…) would start listening in dispose.
  • dispose may read a late field before it is assigned: the field has no initializer, and initState does 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 (an extra_disposables entry that names an extension method, or no method of the type).
  • dispose may 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 a dispose, or a class of the same file extends the State. Flutter’s mixins, such as SingleTickerProviderStateMixin, release nothing of the State and do not count.
  • The class releases the field where dispose does not reach, such as in deactivate, in a callback that initState registers, or in a method that dispose hands 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 unawaited cannot be made callable by adding code alone: in a part whose library does not make it visible, in a file that imports dart:async with hide unawaited, or where unawaited names another function. The other resources of the same State are released all the same.
  • dispose is an expression, asynchronous, a generator, or has no statement and no super.dispose() call; a member named dispose is no method; a name declared in dispose hides the field; or dispose assigns the field.

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.