我有一个父子小部件。父窗口小部件有一个功能。我想从我的子窗口小部件调用那个函数(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
。我如何重写这些代码以获得该功能。
使用回调函数
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();
},
);
}
}
您应该传递函数并调用子窗口小部件
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,
);
}
}