[英]How to call parent widget function from child widget in 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.