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.
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.
我真正想要的是要么在多个屏幕上共享窗口小部件的单个实例,要么让多个实例可以访问一个全局状态。
我如何才能实现这一目标,或者对我的问题有哪些其他推荐的解决方案?
I suggest using Provider and creating a
RPIService
that sends a stream of connectivity status.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
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