我刚刚从子类中调用方法,并得到了this thread中某人的帮助。
我现在正在尝试做的,并且不确定是否不同,是在一个孩子中从同一个父对象的另一个孩子中调用方法。
从视觉上看:
Parent class
- Method()
^
|
Child class
在上面,我可以使用上面提供的链接中的回调函数从子类轻松访问Parent类方法。
这在以下结构中似乎不起作用,并且我无法从我从其他类调用方法所读的任何线程中弄清楚这一点:
Parent class
| |
Child class 1 Child class 2
- Method() <-- callback
此结构的程序处理方式不同吗?有可能还是只能回调到父方法?
答案 0 :(得分:0)
尽管我认为,最好是使用状态更改来更新/触发UI小部件上的调用,但是对于您特殊的情况,delegate pattern
可以工作。这是我愿意做的一个例子。
abstract class TheTrigger { // you can use VoidCallback or whatever, this is just for the demo
void triggerMe();
}
class ChildOneWidget extends StatelessWidget with TheTrigger {
@override
Widget build(BuildContext context) {
return Container(); // add the content of the child one
}
@override
void triggerMe() {
// TODO: implement triggerMe
}
}
class ChildTwoWidget extends StatelessWidget {
final TheTrigger trigger;
const ChildTwoWidget({Key key, this.trigger}) : super(key: key);
@override
Widget build(BuildContext context) {
return Container(
//something here that will trigger "the trigger"
child: RaisedButton(onPressed: () {
trigger?.triggerMe(); // you should use the "?" this will allow a bit more customisation on your widgets, you might want to use it without listener.
}),
);
}
}
class ParrentWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
ChildOneWidget childOneWidget = ChildOneWidget();
ChildTwoWidget childTwoWidget = ChildTwoWidget(trigger: childOneWidget); // here you set the "delegate"
return ListView(
children: <Widget>[childOneWidget, childTwoWidget],
);
}
}
再有一次,这只是一个简单的示例,但是我强烈建议您使用状态来触发子项的更改,您将拥有一个更加灵活的小部件树。
答案 1 :(得分:0)
颤动窗口小部件的工作方式是您的案例中的子窗口小部件位于父窗口小部件树中。在子类2的回调上,您可以使用setState来重建父类,从而重建其任何子类,例如,通过更改子类1中的参数值