Skip to content

state_changed_outside_set_state

Reports an empty setState right after a change of a field, as in _count++; setState(() {});. Make the change inside the callback.

Tier
advisory
Scope
Flutter
Lowest preset
strict
Fix
none

A setState of Flutter’s State whose callback is empty (comments alone count as empty), right after a statement in the same block that changes a field of the object. A change is an assignment, an increment or a decrement, also through an index or a member of the field: _count++; setState(() {});. A call inside an if with no else, such as if (mounted), counts as the call. The violation covers the call.

It does not report:

  • an empty setState with no such change right before it, as in a listener that rebuilds for a change made elsewhere: controller.addListener(() => setState(() {}));
  • a change of a local variable, or one made by a call: _items.add(x);
  • a change that does not stand right before the call;
  • a setState of another object.

setState runs its callback at once, then marks the widget to be built again. The change belongs in the callback, where whoever reads the call sees what the rebuild is for.

Violating
void _add() {
_count++;
setState(() {});
}
Corrected
void _add() {
setState(() => _count++);
}

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.

Write why on the line directly above the suppression:

// Why it stays as written here.
// ignore: assay/state_changed_outside_set_state

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