I have this custom widget:
Widget ButtonsFunction(String text , IconData icon,Function action){
return Column(
children: [
ElevatedButton(
onPressed: () => action,
style: ElevatedButton.styleFrom(
padding: EdgeInsets.all(27.0),
primary: Colors.grey[300],
side: BorderSide(color: Colors.grey , width: 0.5),
elevation: 0,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15.0)),
),
child: Icon(icon , color: Colors.indigo,),
),
SizedBox(height: 8.0,),
Text(text, style: TextStyle(fontWeight: FontWeight.bold),),
],
);
}
and this call:
ButtonsFunction('Corporate', Icons.wallet,() => Navigator.pushNamed(context,'/CorporateMatters')),
But nothing happen when i click on the button, i've tried to write the button code without the function and it works normally but with this function i cant navigate
CodePudding user response:
Call it directly, change this:
onPressed: () => action,
to this:
onPressed: action,
CodePudding user response:
Inside your custom widget you should trigger the function you are passing.
Like this:
onPressed: () => action(),
or this:
onPressed: () => action.call(),
CodePudding user response:
Remove () => and call directly action and I advise you also to use named parameters for clearer code.
onPressed: action,
CodePudding user response:
I prefer using VoidCallback
in this case,
Widget ButtonsFunction(String text, IconData icon, VoidCallback action) {
return Column(
children: [
ElevatedButton(
onPressed: action,
Also note that I am using onPressed: action,
instead of creating anonymous function like onPressed: () => action
. If you like to do this way, you need to use ()
to call the method like onPressed: () => action()
.