Why This Happens
In Flutter, calling setState during build causes the framework to try rebuilding a widget that is already building. This creates an infinite loop. Move state changes to callbacks, initState, or use addPostFrameCallback to defer the change.
The Problem
Widget build(BuildContext context) {
setState(() { _counter++; }); // Called during build!
return Text('$_counter');
}The Fix
Widget build(BuildContext context) {
return ElevatedButton(
onPressed: () => setState(() { _counter++; }),
child: Text('$_counter'),
);
}Step-by-Step Fix
- 1
Identify the error
Look at the error message: setState() or markNeedsBuild() called during build. This means state is being modified in the build method.
- 2
Find the cause
Check the build method for any direct calls to setState or methods that trigger setState.
- 3
Apply the fix
Move the state change to a callback (onPressed, onTap) or use WidgetsBinding.instance.addPostFrameCallback for deferred updates.
Got the actual stack trace?
Paste it into our free AI explainer to get the cause and the fix for your specific case — no signup, nothing to install.
Explain my errorBugsly catches this automatically
Bugsly's AI analyzes this error pattern in real-time, explains what went wrong in plain English, and suggests the exact fix — before your users even report it.
Try Bugsly free