avoid_mounted_in_setstate
Warns when mounted or context.mounted is checked inside a setState callback. If the widget has been disposed, setState itself throws an exception before the callback ever runs, making any mounted check inside it useless.
Why use this rule
Section titled “Why use this rule”A common misconception is that checking mounted inside setState protects against calling setState on a disposed widget. In reality, setState validates the state object immediately when called — if the widget is unmounted, it throws before executing the callback. The mounted check must happen before the setState call, not inside it.
See also: State.mounted | State.setState
class _BadExampleState extends State<BadExample> { Future<void> _loadData() async { final data = await Future.delayed(const Duration(seconds: 1), () => 42);
// mounted check inside setState is too late setState(() { if (mounted) { // If the widget was disposed, setState already threw } });
// context.mounted inside setState is also wrong setState(() { if (context.mounted) { // Same problem } }); }
@override Widget build(BuildContext context) => const SizedBox();}class _GoodExampleState extends State<GoodExample> { Future<void> _loadData() async { final data = await Future.delayed(const Duration(seconds: 1), () => 42);
// Check mounted BEFORE calling setState if (!mounted) return; setState(() { // Safe — we already verified the widget is still mounted });
// Or using context.mounted if (context.mounted) { setState(() { // Also safe }); } }
@override Widget build(BuildContext context) => const SizedBox();}Turning this rule off
Section titled “Turning this rule off”This rule is in the recommended preset, so it is on with
preset: recommended or preset: opinionated. Add it to preset: core with
avoid_mounted_in_setstate: true.
To turn it off:
rules: avoid_mounted_in_setstate: falseTo keep the rule on but skip certain paths, use per-rule exclude.
Options
Section titled “Options”Projects with a state abstraction that does not extend Flutter’s State can
opt that base class into this rule:
many_lints: rules: avoid_mounted_in_setstate: state_base_classes: [AppState]rules: avoid_mounted_in_setstate: state_base_classes: [AppState]| Option | Type | Default | Description |
|---|---|---|---|
state_base_classes |
list of strings | [] |
Additional non-State base classes whose subclasses should be treated as state classes |
Related rules
Section titled “Related rules”avoid_empty_setstate— Don’t call setState with an empty callback.avoid_unnecessary_setstate— Detect unnecessary setState calls in lifecycle methods.avoid_inherited_widget_in_initstate— Don’t look up inherited widgets inside initState.avoid_late_context— Don’t read BuildContext in a late field initializer.