Skip to content

setstate_after_await

Reports a setState call that can run after an await with no mounted check in between. Check mounted after the await.

Tier
blocking
Scope
Flutter
Fix
add if (!mounted) return; before the call

A setState call that can run after an asynchronous gap, with no mounted check between the gap and the call. The violation covers the word setState.

  • The call is setState(…), this.setState(…) or super.setState(…), in a class that extends State or a mixin on it.
  • A gap is an await, or the wait of an await for loop for its next event.
  • A check is a test of Flutter’s mounted (mounted, this.mounted, context.mounted) that the call is reached only through: if (!mounted) return; or if (mounted) … after the gap.
  • Every further await opens the gap again.
  • A check on one path only does not count. After if (careful) { if (!mounted) return; } the gap is still open.
  • In a try whose body awaits, the catch and the finally count as after the gap, even when the body checks.
  • A check inside the callback does not count: setState(() { if (mounted) … }) after an await is reported. By the time the callback runs, setState on a removed State has already thrown.

It does not report a setState before the first await of its function, or a call of something else named setState, such as the function a StatefulBuilder hands to its builder.

While a function waits at an await, the user can leave the page and the framework disposes the State. setState on a State that has left the tree then throws in a debug build and does work for nothing in a release build. The mistake does not show while you try the code, so AI coding agents make it often: they write the happy path and never leave a page while it loads.

Violating
Future<void> _refresh() async {
final items = await widget.repository.load();
setState(() {
_items = items;
});
}
Correctedby leaving when the State is gone
Future<void> _refresh() async {
final items = await widget.repository.load();
if (!mounted) return;
setState(() {
_items = items;
});
}

Or by calling only while it is still there:

Future<void> _save() async {
setState(() => _saving = true);
try {
await widget.repository.save(_draft);
} finally {
if (mounted) setState(() => _saving = false);
}
}

The fix is Add ‘if (!mounted) return;’ before the call. The editor offers it at each violation where it is available, and assay fix applies it across the project (see Fixes). Such a violation’s line in the gate’s message carries [fix available].

The fix adds the line if (!mounted) return; before the statement that holds the call, as in the first correction above, and removes nothing. While the State is mounted, the code does what it did. In a loop the return ends the loop and the function, which is what a removed State needs.

The fix is not available in a function that returns a value, such as Future<bool>, or in a finally block: there, write if (mounted) setState(…); by hand, as in the second correction.

Set under the assay: key of the project’s root analysis_options.yaml.

Rule parameter Default Effect
enabled true false switches the rule off for the whole project.
exclude [] Path globs where the rule is silent.
assay:
rules:
setstate_after_await:
exclude: ["lib/legacy/**"]

Write why on the line directly above the suppression:

// The page route is not dismissible while the upload runs.
// ignore: assay/setstate_after_await
setState(() => _progress = sent / total);

// ignore_for_file: assay/setstate_after_await silences it in a whole file, and // ignore: setstate_after_await without the prefix works too. See Suppressions.

All cases
  • The call is the setState of Flutter’s State on the state the code stands in: setState(…), this.setState(…) or super.setState(…), in a class that extends State or a mixin on it.
  • An asynchronous gap is an await, or the wait of an await for loop for its next event or the end of its stream.
  • A mounted check is a test of a mounted that the Flutter framework declares (mounted, this.mounted, context.mounted), where the call is reached only if it was true. The framework declares mounted on State, BuildContext and its Element, and OverlayEntry. The rule does not look at what it is read from.

It does not report:

  • a setState before the first await of its function, or in a function that does not await;
  • a setState after if (!mounted) return; that follows the gap;
  • a setState inside an if (mounted) that follows the gap;
  • a setState that no path reaches after the gap, such as one after an if whose body awaits and then returns;
  • a call of something else named setState, such as the function a StatefulBuilder hands to its builder;
  • anything in a package that does not use Flutter.

The rule follows the paths through one function in the order the code runs. A setState is reported where, on at least one path, a gap lies behind with no check since.

What closes a gap. A test of mounted, where the test was true:

  • the then-part of if (mounted), of a collection if and of mounted ? … : …;
  • what follows if (!mounted) when its body always leaves, by return, throw, break or continue;
  • the right operand of mounted && …, and the then-part of if (ready && mounted);
  • the else-part of if (!mounted) … else …;
  • the body of while (mounted);
  • the same with mounted == true, mounted != false, mounted == false and mounted != true.

assert(mounted) closes nothing: asserts do not run in a release build.

Only a test of mounted written out closes a gap. Your own flag (if (_disposed) return;), mounted read into a variable first (final here = mounted; if (!here) return;), a helper (if (!_stillHere()) return;) and context?.mounted ?? false on a nullable context do not, and a call of a function that returns Never does not leave as a return or a throw does.

What opens it again. Every further await. After await a(); if (!mounted) return; await b(); the gap is open.

Where paths meet. The gap is open if it is open on any of them. After if (careful) { if (!mounted) return; } the gap is still open: the path where careful is false made no check.

Loops. A round of a loop starts with what the rounds before left behind. A setState before the await in a loop body runs after that await from the second round on, and is reported.

try statements. An error can leave a try body at any point. So the catch and finally of a try whose body awaits start after a gap, even when a check follows the await in the body: the error may have come before the check. What follows the whole statement is judged by the paths on which it completed.

try {
final items = await load();
if (!mounted) return;
setState(() => _items = items); // not reported
} on Exception catch (error) {
setState(() => _error = error); // reported
} finally {
setState(() => _loading = false); // reported
}

Functions inside functions. A closure or a local function starts with the gap of the place where it is declared. Declared after an await with no check since, everything in it is after that gap. An await inside it is a gap of its own and does not suspend the function around it.

  • Where it goes. Before the nearest statement around the call that stands in a block or a switch case: before setState(…); itself, or before if (ready) setState(…);. A call in the body of an if, a loop or a try gets the check in that body.
  • One check per gap. The calls after one gap share one check, before the first of them. assay fix writes it once and counts both violations as fixed. A call after an if whose body got a check gets its own, since the path that skips the body made none.
  • Callbacks. A reported setState in a closure with a block body gets the check inside the closure, which must return nothing, such as a VoidCallback. An expression closure, () => setState(…), gets the check before the statement around it.
  • Layout. The check gets its own line, with the statement’s indentation. It goes above the comment lines directly before the statement, so a comment or a suppression stays with its statement. A statement that follows other code on its line gets the check on that line, directly before it.

The fix is not available, and the violation says so, where:

  • the function returns a value (Future<bool>, int), so leaving it would need one. A function that returns void, Null or a future of either, or a generator, can be left with return;.
  • the call is in a finally block: a return there would drop an error, and the SDK lint control_flow_in_finally reports it. Write if (mounted) setState(…); by hand.
  • the gap is in the statement itself, as in if (await ready()) setState(…);, or the function is written as an expression, with no statement to stand before.
  • mounted at that place would not be the State’s: a local variable, a parameter or another declaration of the method is named mounted, the class declares its own mounted, or the library declares or imports one; and in an extension.