setState() or markNeedsBuild() called during build

setState() or markNeedsBuild() called during build.

Quick Answer

You called setState inside the build method, which triggers an infinite rebuild cycle.

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. 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. 2

    Find the cause

    Check the build method for any direct calls to setState or methods that trigger setState.

  3. 3

    Apply the fix

    Move the state change to a callback (onPressed, onTap) or use WidgetsBinding.instance.addPostFrameCallback for deferred updates.

Bugsly 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