[英]Function as parameter in widget flutter
I am trying to pass function as a parameter in my custom widget:我正在尝试将 function 作为自定义小部件中的参数传递:
_Btn(name: _btnOne, continueBtn: onClick(1)),
I made an onClick function in my main widget:我在我的主要小部件中制作了 onClick function :
onClick(int i) {
switch(i){
case 1:{
print('hello');
}
break;
}
}
and my button widget:和我的按钮小部件:
class _Btn extends StatelessWidget {
final Function btn;
const _GreenBtn({
Key key,
this.btn
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Container(
child: ElevatedButton(
child: Text('hello'),
style: ElevatedButton.styleFrom(
primary: Colors.white,
),
onPressed: () {
btn();
},
),
);
}
}
I am new to flutter, and I am not sure why its not working, if I am doing the next syntax than its ok:我是 flutter 的新手,我不确定为什么它不工作,如果我正在执行下一个语法而不是正常:
_Btn(name: _btnOne, continueBtn: () => print('hello')),
thanks谢谢
Replace your _Btn
with the following:将您的
_Btn
替换为以下内容:
class _Btn extends StatelessWidget {
final Function btn;
final String name;
const _Btn({Key key, this.btn, this.name}) : super(key: key);
@override
Widget build(BuildContext context) {
return Container(
child: ElevatedButton(
child: Text('hello'),
style: ElevatedButton.styleFrom(primary: Colors.white),
onPressed: btn,
),
);
}
}
Now, use it like this:现在,像这样使用它:
_Btn(
name: _btnOne,
btn: () => onClick(1),
)
Why not send the function parameter as a parameter then call onClick(parameter) inside?为什么不发送 function 参数作为参数然后在里面调用 onClick(parameter) 呢?
Like this:像这样:
class _Btn extends StatelessWidget {
final int i;
const _GreenBtn({
Key key,
this.btn
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Container(
child: ElevatedButton(
child: Text('hello'),
style: ElevatedButton.styleFrom(
primary: Colors.white,
),
onPressed: () {
onClick(i) //here
},
),
);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.