本文介绍了将方法作为参数传递给小部件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个自定义按钮小部件:
I have a custom button widget:
class Button extends StatelessWidget {
final String text;
Button(this.text);
@override
Widget build(BuildContext context) {
return Container(
height: 50,
child: SizedBox(
width: double.infinity,
child: RaisedButton(
onPressed: () => {}, // Use the function from parent Widget
child: Padding(
padding: EdgeInsets.symmetric(vertical: 13),
child: Text(
text,
style: TextStyle(fontWeight: FontWeight.bold),
)),
color: COLOR_BLUE,
textColor: Colors.white,
shape:
RoundedRectangleBorder(borderRadius: BorderRadius.circular(25)),
),
),
);
}
}
然后在父窗口小部件中,我想向该按钮窗口小部件传递onPressed
方法:
Then in parent Widget I want to pass a onPressed
method to this button widget:
...
myMethod () => {
// do some stuff
}
...
Padding(
padding: EdgeInsets.only(bottom: 10),
child: Button("Log in", myMethod),
),
...
如何告诉按钮小部件将myMethod
用于onPress
?
How can I tell to a button widget to use the myMethod
for onPress
?
推荐答案
使用VoidCallback
类型,如下所示:
class Button extends StatelessWidget {
final String text;
final VoidCallback callback;
Button(this.text, this.callback);
@override
Widget build(BuildContext context) {
return Container(
height: 50,
child: SizedBox(
width: double.infinity,
child: RaisedButton(
onPressed: callback, // Simply put the function name here, DON'T use ()
child: Padding(
padding: EdgeInsets.symmetric(vertical: 13),
child: Text(
text,
style: TextStyle(fontWeight: FontWeight.bold),
)),
color: COLOR_BLUE,
textColor: Colors.white,
shape:
RoundedRectangleBorder(borderRadius: BorderRadius.circular(25)),
),
),
);
}
}
这篇关于将方法作为参数传递给小部件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!