跨窗口小部件的多个实例的共享状态 [英] flutter share state across multiple instances of a widget
问题描述
在我的flutter应用程序中,我有一个 ConnectivityStatus
小部件,该小部件显示该应用程序与树莓派的当前连接状态.在我的小部件的 initState
中,我订阅了一个计时器,每隔5秒检查一次连接,并相应地更新状态,然后在处置后退订.
In my flutter app, I have a ConnectivityStatus
widget which displays the current connection status of the app to my raspberry pi. In the initState
of my widget, I subscribe to a timer to check the connection every 5 seconds and update the state accordingly, then unsubscribe upon disposal.
问题是,当多个屏幕使用 ConnectivityStatus
小部件时,例如在堆栈导航器设置中,我现在有两个并发订阅,因为没有实例被处置.这会导致发生许多多余的不必要的请求.
The issue is, when multiple screens use the ConnectivityStatus
widget, such as in a stack navigator setup, I now have two concurrent subscriptions as neither instance has disposed. This causes many redundant, unneeded requests to occur.
我真正想要的是要么在多个屏幕上共享窗口小部件的单个实例,要么让多个实例可以访问一个全局状态.
What I really want is to either share a single instance of the widget across multiple screens, or have one global state multiple instances can access.
我该如何实现?或者是针对我的问题的其他推荐解决方案?
How can I achieve this or what are other recommended solutions to my problem?
推荐答案
最简单的方法是使用InheritedWidget将ConnectivityStatus传递给降序的小部件. https://api.flutter.dev/flutter/widgets/InheritedWidget-class.html
The most simple way of achieving this would be to use InheritedWidget to pass the ConnectivityStatus to the descending widgets. https://api.flutter.dev/flutter/widgets/InheritedWidget-class.html
您还可以研究其他状态管理解决方案,例如提供商 https://pub.dev/packages/provider 或集团 https://pub.dev/packages/flutter_bloc
You could also look into other state management solutions such as Provider https://pub.dev/packages/provider or Bloc https://pub.dev/packages/flutter_bloc
这篇关于跨窗口小部件的多个实例的共享状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!