[英]How to Call a function in parent widget from child widget | Flutter
I have a parent and child widget.我有一个父子小部件。 The parent widget has a function.
父小部件有一个 function。 I want to call that function (myParentFunction) from my child widget.
我想从我的子小部件中调用 function (myParentFunction)。 This is the parent widget,
这是父小部件,
class ParentWidget extends StatelessWidget {
void myParentFunction() {
print("This is print from parent");
}
@override
Widget build(BuildContext context) {
return Center(
child: MyCustomButton(),
);
}
}
This is the child widget这是子小部件
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();
},
);
}
}
Here the expected result is when i press the 'Press' button i want the output as This is print from child This is print from parent
.这里的预期结果是当我按下“按下”按钮时,我想要 output,因为
This is print from child This is print from parent
。 How i rewrite this code to get that functionality.我如何重写此代码以获取该功能。
you should pass the function and call in child widget您应该通过 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,
);
}
}
Use a callBack Funtion使用回调函数
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.