Skip to main content

avoid-undisposed-instances

added in: 1.13.0
Pro+
preset: recommended

Warns when an instance that has a dispose method is not assigned to a variable.

Not disposing such instances may lead to memory leaks and should be avoided.

⚙️ Config

Set ignored-instances (default is empty) to ignore instances that are intended to be undisposed (example).

Set ignored-invocations (default is empty) to ignore specific invocation (example).

analysis_options.yaml
dart_code_metrics:
rules:
- avoid-undisposed-instances:
ignored-instances:
- SomeClass
ignored-invocations:
- WithAutoDispose

Example

❌ Bad:

TextSpan(
...
recognizer: LongPressGestureRecognizer() // LINT: This instance is not disposed. Try assigning it to a field and calling 'dispose'.
..onLongPress = _handlePress,
),

✅ Good:

class _SomeState extends State<Some> {
late LongPressGestureRecognizer _longPressRecognizer;


void initState() {
super.initState();

_longPressRecognizer = LongPressGestureRecognizer()
..onLongPress = _handlePress;
}


void dispose() {
_longPressRecognizer.dispose(); // Correct, disposed

super.dispose();
}


Widget build(BuildContext context) {
...
TextSpan(
...
recognizer: _longPressRecognizer,
),
...
}
}

Example with "ignored-instances"

Config
analysis_options.yaml
dart_code_metrics:
rules:
- avoid-undisposed-instances:
ignored-instances:
- LongPressGestureRecognizer

✅ Good:

TextSpan(
...
recognizer: LongPressGestureRecognizer() // Correct, ignored
..onLongPress = _handlePress,
),

Example with "ignored-invocations"

Config
analysis_options.yaml
dart_code_metrics:
rules:
- avoid-undisposed-instances:
ignored-invocations:
- WithAutoDispose

✅ Good:

// Correct, ignored
WithAutoDispose(
...
recognizer: LongPressGestureRecognizer()
..onLongPress = _handlePress,
),