Broadcast data to multiple widgets in Flutter

橙三吉。 提交于 2019-12-18 17:26:50

问题


Is there a way to broadcast data from one widget to other widgets? Similar to a BroadcastReceiver on Android or NSNotificationCenter on iOS.

Specifically, I'm trying to detect when a Navigator pops or pushes a new view. I added navigatorObservers to MaterialApp. And when a widget comes back to the foreground, I want to be able to notify it by broadcasting changes from didPush and didPop with the actual route that's in the current foreground


回答1:


Navigator.push returns a Future that will complete when Navigator.pop is called (and this can optionally be used to pass data back to the widget that called push). So for example suppose your login button has this onPressed handler:

onPressed: () async {
  bool isLoggedIn = await Navigator.pushNamed(context, '/login');
  if (isLoggedIn) {
    // do something
  }
}

When your login page calls Navigator.pop(true), the Future will complete with a value of true which will be assigned to the isLoggedIn variable. (You'll get null if the user uses the back button to return to the previous screen.)

This is how showDialog works as well.



来源:https://stackoverflow.com/questions/44406462/broadcast-data-to-multiple-widgets-in-flutter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!