Skip to main content

dispose-fields

configurable
pro+

Warns when a widget state field is not disposed in dispose method.

Not disposing fields that have a dispose method may lead to memory leaks and should be avoided.

info

This rule will trigger for any field that has dispose, close or cancel methods not called inside the widget's dispose.

⚙️ Config

Set ignore-blocs (default is false) to ignore bloc fields. Enabling this option can be useful if you provide your blocs via BlocProvider (and it closes the passed bloc automatically).

Set ignore-get-x (default is false) to ignore Rx classes from GetX.

analysis_options.yaml
dart_code_metrics:
rules:
- dispose-fields:
ignore-blocs: false
ignore-get-x: false

Example

❌ Bad:

class SomeDisposable implements Disposable {

void dispose() {}
}

class _ShinyWidgetState extends State<ShinyWidget> {
final _someDisposable = SomeDisposable();

// LINT: This field is not disposed, which can lead to a memory leak.
// Try disposing this field in the widget's 'dispose' method.
final _anotherDisposable = SomeDisposable();

void dispose() {
_someDisposable.dispose();

super.dispose();
}
}

✅ Good:

class SomeDisposable implements Disposable {

void dispose() {}
}

class _ShinyWidgetState extends State<ShinyWidget> {
final _someDisposable = SomeDisposable();
final _anotherDisposable = SomeDisposable();

void dispose() {
_someDisposable.dispose();
_anotherDisposable.dispose(); // Correct, disposed

super.dispose();
}
}