Function as parameter in widget flutter
600
Replace your _Btn
with the following:
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),
)
Author by
Coder123
Updated on December 28, 2022Comments
-
Coder123 over 1 year
I am trying to pass function as a parameter in my custom widget:
_Btn(name: _btnOne, continueBtn: onClick(1)),
I made an onClick function in my main widget:
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:
_Btn(name: _btnOne, continueBtn: () => print('hello')),
thanks
-
Simon Sot about 3 yearsPass argument to function when you invoke it, not when you pass it down, delete (1) in dependency injection and pass 1 in onPressed
-
-
Coder123 about 3 yearsbecause the method is not defined for the btn widget
-
Coder123 about 3 yearsdo you mean to remove the brackets?
-
CopsOnRoad about 3 yearsThere are many things I changed to make it work, can you use the entire code I posted and not just one thing.