Davinci Cake
Davinci Cake

Reputation: 79

Flutter: how to execute multiple functions in a single button

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,

Upvotes: 1

Views: 1596

Answers (3)

alkndoom
alkndoom

Reputation: 1

You need to declare a constructor which takes onTap function as a parameter.

class MyButton extends StatelessWidget {
  final Function onTap;
  const MyButton ({Key? key, this.onTap,}) : super(key: key);
}

Since the onTap parameter needs a function as argument, you simply write a function that runs your functions.

MyButton(
  onTap: () {
    your_function1();
    your_function2();
  },
)

Upvotes: 0

Manpreet Singh Pandher
Manpreet Singh Pandher

Reputation: 257

Declare function variable:

 final Function onTap;

and call widget.onTap with round brackets as below:

 onTap: (){
 widget.onTap();
 setState(() {
    _clicked = !_clicked;
  });
 }

Upvotes: 0

gnaungayan
gnaungayan

Reputation: 522

This is usually how I do it.

onTap: () {
    widget.onTap();
    your_function_here();
  },

Upvotes: 1

Related Questions