Khalil Bz
Khalil Bz

Reputation: 607

Calling setState() during build without user interaction

What I did :

@override
Widget build(BuildContext context) {
    StaticClass.currentContext = context;
    StaticClass.currentSetState = this.setState;
    return ... ;
}
fcm.configure( onMessage: (){
    StaticClass.currentSetState((){
        Navigator.pushNamed(StaticClass.currentContext, "/notifications");
  });
});

What happened :

 ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══
...
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.
...

Explanations :

What I want :

OR

OR


Please Help I'm stuck here

Upvotes: 8

Views: 12728

Answers (1)

Miguel Ruivo
Miguel Ruivo

Reputation: 17756

You can call setState after rendering is done by adding a post frame callback with addPostFrameCallback method. This will be called only once and after build process is done.

WidgetsBinding.instance.addPostFrameCallback((_) => setState(() {}));

Upvotes: 37

Related Questions