在构建过程中无需用户交互就调用setState() [英] Calling setState() during build without user interaction
本文介绍了在构建过程中无需用户交互就调用setState()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我做了什么:
- 我在flutter应用程序中集成了FCM(Firebase云消息传递)。
- 我在其中共享了每个页面的
上下文
和setState()
在页面的所有构建函数中都调用了带有这两行的静态变量:
- I have integrated FCM (Firebase Cloud Messaging) in my flutter app.
- I shared the
context
and thesetState()
of each page in static variables with these two lines getting called in all the build functions of my pages :
@override
Widget build(BuildContext context) {
StaticClass.currentContext = context;
StaticClass.currentSetState = this.setState;
return ... ;
}
- I创建了一个回调,以在应用程序运行时处理即将到来的通知
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())
- 通过用户交互调用此函数时不会发生此问题
什么我想要:
- 有没有办法修复我的代码,或者我做错了什么?
OR
- 是否有触发onMessage()时转到其他页面的其他解决方案?
OR
- 有没有办法知道构建函数何时完成,setState()没有任何问题?
请帮助我被困在这里
推荐答案
渲染完成后,您可以通过添加后框架来调用 setState
使用 addPostFrameCallback 方法进行回调。在构建过程完成后,此操作将仅一次。
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(() {}));
这篇关于在构建过程中无需用户交互就调用setState()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文