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
What it reports
Section titled “What it reports”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(…)orsuper.setState(…), in a class that extendsStateor a mixin on it. - A gap is an
await, or the wait of anawait forloop 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;orif (mounted) …after the gap. - Every further
awaitopens 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
trywhose body awaits, thecatchand thefinallycount as after the gap, even when the body checks. - A check inside the callback does not count:
setState(() { if (mounted) … })after anawaitis reported. By the time the callback runs,setStateon a removedStatehas 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.
Example
Section titled “Example”Future<void> _refresh() async { final items = await widget.repository.load(); setState(() { _items = items; });}State is goneFuture<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.
Rule parameters
Section titled “Rule parameters”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/**"]Suppressing it
Section titled “Suppressing it”Write why on the line directly above the suppression:
// The page route is not dismissible while the upload runs.// ignore: assay/setstate_after_awaitsetState(() => _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.
Details
Section titled “Details”All cases
What it reports, in full
Section titled “What it reports, in full”- The call is the
setStateof Flutter’sStateon the state the code stands in:setState(…),this.setState(…)orsuper.setState(…), in a class that extendsStateor a mixin on it. - An asynchronous gap is an
await, or the wait of anawait forloop for its next event or the end of its stream. - A
mountedcheck is a test of amountedthat the Flutter framework declares (mounted,this.mounted,context.mounted), where the call is reached only if it was true. The framework declaresmountedonState,BuildContextand itsElement, andOverlayEntry. The rule does not look at what it is read from.
It does not report:
- a
setStatebefore the firstawaitof its function, or in a function that does not await; - a
setStateafterif (!mounted) return;that follows the gap; - a
setStateinside anif (mounted)that follows the gap; - a
setStatethat no path reaches after the gap, such as one after anifwhose body awaits and then returns; - a call of something else named
setState, such as the function aStatefulBuilderhands to its builder; - anything in a package that does not use Flutter.
How the rule decides
Section titled “How the rule decides”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 collectionifand ofmounted ? … : …; - what follows
if (!mounted)when its body always leaves, byreturn,throw,breakorcontinue; - the right operand of
mounted && …, and the then-part ofif (ready && mounted); - the else-part of
if (!mounted) … else …; - the body of
while (mounted); - the same with
mounted == true,mounted != false,mounted == falseandmounted != 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.
How the fix decides
Section titled “How the fix decides”- Where it goes. Before the nearest statement around the call that stands in a block or a
switchcase: beforesetState(…);itself, or beforeif (ready) setState(…);. A call in the body of anif, a loop or atrygets the check in that body. - One check per gap. The calls after one gap share one check, before the first of them.
assay fixwrites it once and counts both violations as fixed. A call after anifwhose body got a check gets its own, since the path that skips the body made none. - Callbacks. A reported
setStatein a closure with a block body gets the check inside the closure, which must return nothing, such as aVoidCallback. 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 returnsvoid,Nullor a future of either, or a generator, can be left withreturn;. - the call is in a
finallyblock: areturnthere would drop an error, and the SDK lintcontrol_flow_in_finallyreports it. Writeif (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. mountedat that place would not be theState’s: a local variable, a parameter or another declaration of the method is namedmounted, the class declares its ownmounted, or the library declares or imports one; and in an extension.