avoid-unnecessary-setstate

Path
lint/correctness/avoid-unnecessary-setstate
Default
On (recommended)
Origin
Falcon
Domain
flutter
Rule
172 of 512
recommendedflutter

Avoid setState during build, initState, or didUpdateWidget. Synchronous local method calls are followed transitively; deferred closures and async methods are excluded.

Invalid

example.dartdart
import 'package:flutter/material.dart';
class S extends State<StatefulWidget> { int x=0;
void initState() { setState(() { x++; }); }
Widget build(BuildContext context) { setState(() { x++; }); return Text(''); }
void didUpdateWidget(StatefulWidget old) { setState(() { x++; }); }
}
class Explicit extends State<StatefulWidget> { void initState() { this.setState(() {}); } }
class Helpers extends State<StatefulWidget> { void update() { setState(() {}); } void initState() { update(); } }
Update state directly instead of calling `setState` during this lifecycle method.
2class S extends State<StatefulWidget> { int x=0;
3void initState() { setState(() { x++; }); }
Update state directly instead of calling `setState` during this lifecycle method.
3void initState() { setState(() { x++; }); }
4Widget build(BuildContext context) { setState(() { x++; }); return Text(''); }
Update state directly instead of calling `setState` during this lifecycle method.
4Widget build(BuildContext context) { setState(() { x++; }); return Text(''); }
5void didUpdateWidget(StatefulWidget old) { setState(() { x++; }); }
Update state directly instead of calling `setState` during this lifecycle method.
6}
7class Explicit extends State<StatefulWidget> { void initState() { this.setState(() {}); } }
Update state directly instead of calling `setState` during this lifecycle method.
7class Explicit extends State<StatefulWidget> { void initState() { this.setState(() {}); } }
8class Helpers extends State<StatefulWidget> { void update() { setState(() {}); } void initState() { update(); } }

Valid

example.dartdart
import 'package:flutter/material.dart';
class S extends State<StatefulWidget> { int x=0;
void update() { setState(() { x++; }); }
void didChangeDependencies() { setState(() { x++; }); }
Widget build(BuildContext context) { return ElevatedButton(onPressed: () { setState(() { x++; }); }, child: Text('')); }
void initState() { Future.delayed(Duration.zero, () { setState(() { x++; }); }); }
}
class Other { void setState(Function fn) {} void initState() { setState(() {}); } }

Configure avoid-unnecessary-setstate

Set its severity in falcon.json. See the configuration guide.

falcon.jsonjson
{
  "linter": {
    "rules": {
      "correctness": {
        "avoid-unnecessary-setstate": "error"
      }
    }
  }
}

Or silence one occurrence with a suppression comment; the reason is required.

example.dartdart
// falcon-ignore lint/correctness/avoid-unnecessary-setstate: <reason>