Function 在控件颤振中用作参数
我正在尝试将函数作为参数传递到自定义小部件中:Function 在控件颤振中用作参数,function,flutter,Function,Flutter,我正在尝试将函数作为参数传递到自定义小部件中: _Btn(name: _btnOne, continueBtn: onClick(1)), 我在主窗口小部件中创建了onClick函数: onClick(int i) { switch(i){ case 1:{ print('hello'); } break; } } 和我的按钮小部件: class _Btn extends StatelessWidget { final
_Btn(name: _btnOne, continueBtn: onClick(1)),
我在主窗口小部件中创建了onClick函数:
onClick(int i) {
switch(i){
case 1:{
print('hello');
}
break;
}
}
和我的按钮小部件:
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();
},
),
);
}
}
我是个新手,我不知道为什么它不起作用,
如果我正在执行下一个语法,那么它是确定的:
_Btn(name: _btnOne, continueBtn: () => print('hello')),
谢谢用以下内容替换您的
\u Btn
:
class\u Btn扩展了无状态小部件{
最终功能btn;
最后的字符串名;
const_Btn({Key-Key,this.Btn,this.name}):super(Key:Key);
@凌驾
小部件构建(构建上下文){
返回容器(
儿童:升降按钮(
child:Text('hello'),
样式:ElevatedButton.styleFrom(原色:白色),
按:btn,
),
);
}
}
现在,像这样使用它:
_Btn(
name: _btnOne,
btn: () => onClick(1),
)
为什么不将函数参数作为参数发送,然后在内部调用onClick(parameter) 像这样:
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
},
),
);
}
}
调用函数时将参数传递给函数,而不是向下传递时,在依赖项注入中删除(1)并在OnPressed中传递1,因为该方法未为btn Widget定义。您的意思是删除括号吗?我做了许多更改以使其工作,您能否使用我发布的整个代码,而不仅仅是一件事。