How to fix "setState() or markNeedsBuild() called during build" error in Flutter
The setState() or markNeedsBuild() called during build error is common in Flutter when working with dynamic UIs or triggering state changes at the wrong time. This post explains how to fix it and prevent it in your projects.
Why does the “setState() or markNeedsBuild() called during build” error occur?
This error means you’re trying to call setState()
(or trigger a rebuild) while Flutter is already in the middle of building widgets. This can cause unpredictable behavior and is usually a sign that state changes are happening at the wrong time in the widget lifecycle.
Example scenario:
You might see this error if you call setState()
inside the build()
method, or if you try to show a dialog or a snackbar before the build process is complete.
How to fix the “setState() or markNeedsBuild() called during build” error
Here are the steps to resolve this error:
1. Avoid calling setState() inside build()
Never call setState()
directly inside the build()
method. Instead, trigger state changes in response to user actions or lifecycle events.
2. Use WidgetsBinding.instance.addPostFrameCallback
If you need to trigger a state change or show a dialog/snackbar after the build is complete, use:
WidgetsBinding.instance.addPostFrameCallback((_) {
// Your code here, e.g. setState(), showDialog, etc.
});
Or, using SchedulerBinding:
SchedulerBinding.instance.addPostFrameCallback((_) {
// Your code here
Navigator.push(
context,
MaterialPageRoute(builder: (context) => NextPage()),
);
});
This ensures your code runs after the current frame is rendered, avoiding conflicts with the build process.
Best practices to avoid this error
- Only call
setState()
in response to user actions or asynchronous events, not during build. - Use
addPostFrameCallback
for actions that need to happen after the widget tree is built. - Read the full error message and stack trace to find where the problematic call is happening.
Conclusion
The “setState() or markNeedsBuild() called during build” error in Flutter is common, but easy to fix by managing state changes at the right time. Following best practices will help you avoid this error and build more stable Flutter apps.
Need help with Flutter or cross-platform development? Our team is here to help you debug and build better apps!
Click the button below to book a free consultation with us 🤝
Book Free Consultation