繁体   English   中英

如何从子小部件调用父小部件中的 function | Flutter

[英]How to Call a function in parent widget from child widget | Flutter

我有一个父子小部件。 父小部件有一个 function。 我想从我的子小部件中调用 function (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();
      },
    );
  }
}

这里的预期结果是当我按下“按下”按钮时,我想要 output,因为This is print from child This is print from parent 我如何重写此代码以获取该功能。

您应该通过 function 并调用子小部件

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,
    );
  }
}

使用回调函数


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();
      },
    );
  }
}

暂无
暂无

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

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