简体   繁体   English

从父级调用子小部件中的方法

[英]Call method in sub widget from parent

I have a method in my parent widget that runs and updates a boolean.我的父小部件中有一个方法可以运行和更新 boolean。 Whenever the value is changed, a method needs to be run in a child widget, using the changed value.每当更改值时,都需要在子窗口小部件中运行一个方法,使用更改后的值。 What is the best way to trigger that action from the parent?从父母那里触发该动作的最佳方式是什么?

Both widgets are stateful widgets.这两个小部件都是有状态的小部件。

You could either inject the parent's method as a callback to the child or dispatch a notification from the child and then listen for it in the parent.您可以将父级的方法作为回调注入子级,也可以从子级发送通知,然后在父级中监听它。

The latter is a cleaner and more reusable way, since it'll improve your child reusability.后者是一种更清洁、更可重用的方式,因为它会提高您孩子的可重用性。

You can check here for a very good guide on how to do it!您可以在此处查看有关如何操作的非常好的指南!

The answer from magicleon94 was pretty good, and would have worked if I needed to update a widget with new information. magicleon94 的答案非常好,如果我需要用新信息更新小部件,它会起作用。 I will probably reference that for some other issues I am working on.对于我正在处理的其他一些问题,我可能会参考它。 For this issue, I needed to run a method to return markers for a mapWidget, based on data from a parent, when that data changed.对于这个问题,当数据发生变化时,我需要运行一个方法来根据来自父级的数据返回 mapWidget 的标记。 I found the best way to do that was using a streamController, as outlined by this StackOverflow post .我发现最好的方法是使用 streamController,正如StackOverflow 帖子所述。 Whenever I updated the value, I called add on the stream, and then received the update in my child class.每当我更新值时,我都会在 stream 上调用 add,然后在我的孩子 class 中收到更新。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM