prefer_single_setstate
Flags methods in State subclasses that contain multiple setState() calls at the same scope level. Each setState() call schedules a rebuild, so calling it multiple times in the same synchronous method triggers redundant rebuilds that can be avoided by merging all state mutations into a single call.
Why use this rule
Section titled “Why use this rule”Multiple setState() calls in the same method cause Flutter to schedule multiple rebuilds in the same frame. While Flutter coalesces them into one actual rebuild, the pattern is misleading and fragile. Merging mutations into a single setState() makes the code clearer and avoids accidental intermediate states if the framework behavior changes.
See also: State.setState()
class _BadState extends State<BadWidget> { String _a = ''; String _b = '';
void _update() { setState(() { _a = 'Hello'; }); setState(() { _b = 'World'; }); }
// Even with code in between: void _updateWithGap() { setState(() { _a = 'Hello'; }); debugPrint('between'); setState(() { _b = 'World'; }); }}class _GoodState extends State<GoodWidget> { String _a = ''; String _b = '';
void _update() { setState(() { _a = 'Hello'; _b = 'World'; }); }}
// setState in separate closures is fine (different scopes):void _setup() { final callback1 = () { setState(() { _data = 'a'; }); }; final callback2 = () { setState(() { _data = 'b'; }); };}
// setState in different methods is fine:void _update1() { setState(() { _data = 'Hello'; });}void _update2() { setState(() { _data = 'World'; });}Turning this rule off
Section titled “Turning this rule off”This rule is in the opinionated preset, so it is on with
preset: opinionated, or by name:
rules: prefer_single_setstate: trueTo turn it off again:
rules: prefer_single_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: prefer_single_setstate: state_base_classes: [AppState]rules: prefer_single_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_accessing_other_classes_private_members— Make the underscore mean what everyone reads it as.avoid_commented_out_code— Detect and flag commented-out code.avoid_complex_conditions— Keep boolean conditions within an operand budget.avoid_deep_nesting— Keep control flow within a nesting budget.