在Flutter中将数据广播到多个小部件 [英] Broadcast data to multiple widgets in Flutter

查看:1119
本文介绍了在Flutter中将数据广播到多个小部件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法将数据从一个小部件广播到其他小部件?类似于Android上的BroadcastReceiver或iOS上的NSNotificationCenter。

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

具体来说,我试图检测导航器何时弹出或推送新视图。我将navigatorObservers添加到MaterialApp。当一个小部件回到前台时,我希望能够通过广播来自didPush和didPop的更改来通知它,其中包含当前前景中的实际路径

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

推荐答案

Navigator.push 返回 Future ,它将在 Navigator.pop (这可以选择用于将数据传递回名为 push 的小部件)。因此,例如假设您的登录按钮具有此 onPressed 处理程序:

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
  }
}

当您的登录页面调用 Navigator.pop(true)时, Future 将完成值 true 将分配给 isLoggedIn 变量。 (如果用户使用后退按钮返回上一个屏幕,您将获得 null 。)

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.)

这个 showDialog 是如何工作的。

这篇关于在Flutter中将数据广播到多个小部件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆