在没有用户交互的情况下在构建期间调用 setState()

Calling setState() during build without user interaction

我做了什么:

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

发生了什么:

 ══╡ 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.
...

解释:

我想要的:


请帮助我卡在这里

您可以在渲染完成后调用 setState,方法是使用 addPostFrameCallback 方法添加 post 帧回调。这只会被调用一次并且在构建过程完成之后。

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