Skip to main content

dispose-class-fields

added in: 1.21.0
⚙️
Pro+
preset: recommended

Warns when a field is not disposed in a class's dispose method.

Not disposing fields that have a dispose, close or cancel methods may lead to memory leaks and should be avoided.

info

This rule will not trigger if the class does not declare any of the configured methods.

If the class declares multiple methods (e.g. dispose and close), then the rule will use the first one from the configuration list.

⚙️ Config

Set methods (default is [dispose, close, cancel]) to configure the list of methods to check.

analysis_options.yaml
dart_code_metrics:
rules:
- dispose-class-fields:
methods:
- someCustomDispose

Example

❌ Bad:

class SomeDisposable implements Disposable {

void dispose() {}
}

class SomeClass {
final _someDisposable = SomeDisposable();
final _anotherDisposable = SomeDisposable(); // LINT: This field is not disposed, which can lead to a memory leak.

void dispose() {
_someDisposable.dispose();
}
}

✅ Good:

class SomeDisposable implements Disposable {

void dispose() {}
}

class SomeClass {
final _someDisposable = SomeDisposable();
final _anotherDisposable = SomeDisposable(); // Correct, disposed

void dispose() {
_someDisposable.dispose();
_anotherDisposable.dispose();
}
}