setState() or markNeedsBuild called during build

后端 未结 6 1664
自闭症患者
自闭症患者 2020-12-04 16:14
class MyHome extends StatefulWidget {
  @override
  State createState() => new MyHomePage2();
}

class MyHomePage2 extends State

        
6条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-04 17:06

    In my case I was calling setState method before build method complete process of building widgets.

    You can face this error if you are showing snack bar or alert dialog before the completion of build method and in many other cases. so in such situation use below call back function.

    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()));
    });
    

提交回复
热议问题