setState() or markNeedsBuild called during build

In my case I was calling the setState method before the build method had completed the process of building the widgets.

You can face this error if you are showing a snackBar or an alertDialog before the completion of the build method, as well as in many other cases. So, in such cases you should use a call back function as shown below:

WidgetsBinding.instance.addPostFrameCallback((_){

  // Add Your Code here.

});

or you can also use SchedulerBinding which does the same:

SchedulerBinding.instance.addPostFrameCallback((_) {

  // add your code here.

  Navigator.push(
        context,
        new MaterialPageRoute(
            builder: (context) => NextPage()));
});

Leave a Comment