Skip to main content

dispose-class-fields

added in: 1.21.0
⚙️
Pro+

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]) to configure the list of methods to check.

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

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

✅ Good:

class SomeDisposable implements Disposable {

void dispose() {}
}

class SomeClass {
final _someDisposable = SomeDisposable();
final _anotherDisposable = SomeDisposable();

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