[Solved] setState() or markNeedsBuild() called during build Error

In this post, we are going to show you how to solve "setState() or markNeedsBuild() called during build" error in the Flutter app. This error occurs when you call setState in the Widget build method.

══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞════════════════════════════
The following assertion was thrown building Home(dirty, dependencies:
[_LocalizationsScope-[GlobalKey#375ab]], state: _HomeState#aeb2b):
setState() or markNeedsBuild() called during build.
This Overlay widget cannot be marked as needing to build because the framework is already in the
process of building widgets.  A widget can be marked as needing to be built during the build phase
only if one of its ancestors is currently building. This exception is allowed because the framework
builds parent widgets before children, which means a dirty descendant will always be built.
Otherwise, the framework might not visit this widget during this build phase.
The widget on which setState() or markNeedsBuild() was called was:
  Overlay-[LabeledGlobalKey<OverlayState>#29237]
The widget which was currently being built when the offending call was made was:

This error happens when you try to show a snack bar or alert dialog before the completion of the widget build. For example:

Widget build(BuildContext context) {

  showDialog(
    context: context,
    builder: (BuildContext context) {
        return AlertDialog(
          title: Text("How are you?"),
        );
  }); //Error: setState() or markNeedsBuild() called during build.

  return Scaffold(
        body: Center(
          child: Text("Hello World")      
        )
  );
} 

Here, showDialog() the method is called the inside widget build method, which causes the run time error. In your case, there must be another scenario of code inside widget build which is using setState.

To solve this error, you must wrap your current code with:

Widget build(BuildContext context) {

  Future.delayed(Duration.zero,(){
       //your code goes here
  });

  return Scaffold(
        //widget tree
  );
} 

If you want to call showDialog() or want to execute any other kind of code that calls setState(), then use Future.delayed() a method  like below:

Widget build(BuildContext context) {

  Future.delayed(Duration.zero,(){
    showDialog(
      context: context,
      builder: (BuildContext context) {
          return AlertDialog(
            title: Text("How are you?"),
          );
    });
  });

  return Scaffold(
        body: Center(
          child: Text("Hello World")      
        )
  );
} 

In this way, you can solve "setState() or markNeedsBuild() called during build" error in the Flutter app.

No any Comments on this Article


Please Wait...