[英]How does the flutter parent component call a child component?
As mentioned, you need to use a callback.如前所述,您需要使用回调。 What this means it that you pass a function to your child that it calls when it needs to.这意味着您将一个函数传递给您的孩子,它会在需要时调用。 You'll be working from the inside up, not top down.你将从内而上而不是自上而下地工作。
You'll store the function as a member variable and when your child is clicked you'll call that function.您将该函数存储为一个成员变量,当您的孩子被点击时,您将调用该函数。 The function will be called in your parent, you can pass whatever data you want back to the parent just like calling a normal function.该函数将在您的父级中调用,您可以像调用普通函数一样将任何您想要的数据传递回父级。
Here's some pseudo-code you can use to make the adjustment这是一些您可以用来进行调整的伪代码
class son extends StatelessWidget {
Function onClicked;
son({this.onClicked});
Widget build(...) {
return GestureDetector(
child: Container(...),
onTap: onClicked
)
}
}
class father extends StatelessWidget {
Widget build(...) {
return Container(
child:son(onClicked: _clicked)
)
}
void _clicked() {
print('clicked');
}
}
Also, Definitely change your class names to start with a Capital letter.此外,一定要将您的班级名称更改为以大写字母开头。
class Father extends StatelessWidget {
var child;
@override
Widget build(BuildContext context) {
child = son();
return Scaffold(
body: child,
floatingActionButton: FloatingActionButton(
onPressed: () => child?.childFunction(),
),
);
}
}
class Son extends StatelessWidget {
void childFunction() => print('called in child widget');
@override
Widget build(BuildContext context) {
return Container(
color: Colors.red,
);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.