小部件间通信 [英] Inter Widget communication

查看:61
本文介绍了小部件间通信的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以通过通知/事件总线之类的工具进行小部件间的通信?

Is it possible to do inter widget communication via something like a notification/event bus?

我需要能够告诉一个窗口小部件对另一个窗口中发生的事情做出反应,并且不想创建硬链接.

I need to be able to tell one widget to react to something that happened in another and didn't want to create a hard link.

仅当通知侦听器在窗口小部件树中高于两个窗口小部件时,才会触发通知侦听器.

The notification listener will only fire is if it is higher in the widget tree than both of the widgets so that isn't probably a viable solution.

推荐答案

根据您的用例,有很多方法可以做到这一点.

There are lots of ways to do this depending on your use case.

您可以让它们是 AnimatedWidget ValueNotifier 动画示例.

You could have them be AnimatedWidgets that are passed a ValueNotifier or ChangeNotifier as the listenable. You can see this pattern in the Gallery's animation example.

您可以使用 StreamBuilder 来自动重建小部件当新事件出现在 Stream .在Flutter主仓库中没有很多这样的例子,但是一旦开始使用插件或进行网络I/O,您可能会需要它.

You could use StreamBuilder to have your widgets rebuild automatically when new events come in on a Stream. There aren't a lot of examples of this in the main Flutter repo, but it's something that you're likely to need once you start using plugins or doing network I/O.

您可以使用 GlobalKey 来获取 currentState ,在另一个方法上有一个State调用方法.这是快餐店的工作方式( example ).

You could use a GlobalKey to get currentState and have one State call methods on the other. This is how snackbars work (example).

您还可以扩展 InheritedWidget 为小部件提供信息不会作为构造函数参数传递,并且当这些信息发生更改时,它们会自动标记为要重建.例如,这就是 Theme 的工作方式.

You can also extend InheritedWidget to provide widgets with information that wasn't passed as a constructor argument, and they'll automatically be marked for rebuild when that information changes. This is how Themes work, for example.

如果您可以提供有关小部件的功能/它们之间的关系或理想的代码段的更多详细信息,我可以帮助您确定哪种方法最适合您的情况.

If you can provide more details on what your widgets do / what their relationship is, or ideally a code snippet I can help you decide which approach would make the most sense for your situation.

这篇关于小部件间通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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