in Flutter I have made a custom button that does a small animation when pressing it. The issue is that when I add a VoidCallBack
function, which is a parameter that I give to the button widget, to the same onTap
, then the function does not get executed whilst the animation does.
I did find this question ( how do we execute two function in single button pressed in flutter) that seems to be similar to mine but I have tried the suggestions and they do not work for me.
Here is a code snippet of when Im trying to use the button widget:
MyButton (
onTap = () {
print(_isSelected);
setState(() {
_isSelected[0] = !_isSelected[0];
});
},
)
Also I dont know if it makes a difference but Ive tried it both with and without the setState
part.
Then in the button itself I do:
onTap: () {
widget.onTap;
setState(() {
_clicked = !_clicked;
});
},
I also tried to do this, like in the other stackOverflow question which had the same result:
onTap: () => [
widget.onTap,
{
setState(() {
_clicked = !_clicked;
})
}
],
Though it does work if I only use the parameter: onTap: widget.onTap,
CodePudding user response:
This is usually how I do it.
onTap: () {
widget.onTap();
your_function_here();
},
CodePudding user response:
Declare function variable:
final Function onTap;
and call widget.onTap with round brackets as below:
onTap: (){
widget.onTap();
setState(() {
_clicked = !_clicked;
});
}
CodePudding user response:
class MyButton extends StatelessWidget {
final onTap;
const MyButton ({Key? key, this.onTap,}) : super(key: key);
}
MyButton(
onTap: () {
your_function1();
your_function2();
},
)