【问题标题】:How to Call a function in parent widget from child widget | Flutter如何从子小部件调用父小部件中的函数 |扑
【发布时间】:2021-12-30 01:55:52
【问题描述】:

我有一个父子小部件。父小部件具有功能。我想从我的子小部件中调用该函数(myParentFunction)。这是父小部件,

class ParentWidget extends StatelessWidget {

  void myParentFunction() {
    print("This is print from parent");
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: MyCustomButton(),
    );
  }
}

这是子部件

class MyCustomButton extends StatelessWidget {

  void myChildFunction() {
    print("This is print from child");
    //Here i want to call the myParentFunction()
  }

  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      child: Text('Press'),
      onPressed: () {
        newFunction();
      },
    );
  }
}

这里的预期结果是当我按下“按下”按钮时,我希望输出为This is print from child This is print from parent。我如何重写此代码以获得该功能。

【问题讨论】:

    标签: flutter dart flutter-layout flutter-web flutter-animation


    【解决方案1】:

    使用回调函数

    
    class ParentWidget extends StatelessWidget {
      void myParentFunction() {
        print("This is print from parent");
      }
    
      @override
      Widget build(BuildContext context) {
        return Center(
          child: MyCustomButton(
            callback: () {
              myParentFunction();
            },
          ),
        );
      }
    }
    
    class MyCustomButton extends StatelessWidget {
      final VoidCallback callback;
      MyCustomButton({
        Key? key,
        required this.callback,
      }) : super(key: key);
      void myChildFunction() {
        print("This is print from child");
        //Here i want to call the myParentFunction()
      }
    
      @override
      Widget build(BuildContext context) {
        return ElevatedButton(
          child: Text('Press'),
           onPressed: () {
            callback();
          },
        );
      }
    }
    

    【讨论】:

      【解决方案2】:

      您应该传递函数并在子窗口小部件中调用

      class ParentWidget extends StatelessWidget {
      
        void myParentFunction() {
          print("This is print from parent");
        }
      
        @override
        Widget build(BuildContext context) {
          return Center(
            child: MyCustomButton(myParentFunction),
          );
        }
      }
      
      class MyCustomButton extends StatelessWidget {
      
      final Function onTap;
      
      MyCustomButton(this.onTap);
        @override
        Widget build(BuildContext context) {
          return ElevatedButton(
            child: Text('Press'),
            onPressed: onTap,
          );
        }
      }
      
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-05-04
        • 2020-04-23
        • 2020-01-01
        • 2021-02-17
        • 1970-01-01
        • 2021-12-04
        • 1970-01-01
        • 2019-09-21
        相关资源
        最近更新 更多