【问题标题】:Flutter - Calling methods from one child class to another child classFlutter - 从一个子类调用方法到另一个子类
【发布时间】:2019-07-25 12:57:55
【问题描述】:

我刚刚在 this thread 某人的帮助下从一个子类中调用方法。

我现在想要做的,我不确定它是否不同,是从同一个父母的另一个孩子的一个孩子中调用一个方法。

视觉效果:

Parent class
  - Method()
      ^
      |
  Child class

在上面,我可以使用上面提供的链接中的回调函数轻松地从子类访问父类方法。

这在下面的结构中似乎不起作用,我无法从我读过的关于从其他类调用方法的任何线程中弄清楚这一点:

      Parent class
      |           |
Child class 1    Child class 2 
     - Method()  <-- callback

这个结构的过程是否有不同的处理方式?是否有可能或者您只能回调到父方法?

【问题讨论】:

    标签: callback flutter


    【解决方案1】:

    flutter 小部件的工作方式是您案例中的子小部件位于父小部件树中。在 Child 类 2 的回调中,您可以使用 setState 来重建父级,从而重建其任何子级,例如通过更改 Child 类 1 中的参数值

    【讨论】:

      【解决方案2】:

      虽然我认为,在颤振中,最好使用状态更改来更新/触发 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], 
          );
        }
      }
      

      再一次,这只是一个关于如何做到这一点的愚蠢示例,但我强烈建议使用状态来触发子级的更改,您将拥有一个更灵活的小部件树。

      【讨论】:

      • 感谢@danypata 的回复。我无法让这个工作。您调用小部件的最后一部分告诉我:“参数类型 'Type' 不能分配给参数类型 'TheTrigger'。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-07
      • 1970-01-01
      相关资源
      最近更新 更多