Search code examples
functionflutterdartfunction-call

Call function in onTap method directly or using fat operator in Dart/Flutter?


I have created a function in my app which makes a custom widget according to my need. Here is the code for the function

Widget customCircularButton(
  {String title, String subTitle, String img, void Function() onTap}) {
return Column(
  mainAxisSize: MainAxisSize.min,
  children: [
    GestureDetector(
      onTap: onTap,
      child: CircleAvatar(
        radius: screenWidth(context) / 6,
        backgroundColor: pColor,
        child: CircleAvatar(
          radius: screenWidth(context) / 6 - 2,
          backgroundColor: Colors.white,
          backgroundImage: Image.asset(img).image,
        ),
      ),
    ),
    Container(
      margin: EdgeInsets.all(5),
      child: Text(
        title,
        style: TextStyle(fontWeight: FontWeight.bold, fontSize: 20),
      ),
    ),
    Container(
        margin: EdgeInsets.all(5),
        width: screenWidth(context) / 3,
        child: Text(
          subTitle,
          style: TextStyle(fontWeight: FontWeight.w300, fontSize: 12),
          textAlign: TextAlign.center,
        ))
  ],
);

}

So to call this function into my widget i call it like this

Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: [
          customCircularButton(
            title: 'Donate',
            subTitle: 'Donate/Buy food for needy',
            img: 'assets/images/donate-food.png',
            onTap: donateDiaolg,
          ),
          customCircularButton(
              title: 'Become Volunteer',
              subTitle: 'Distribute food to the needy',
              img: 'assets/images/become-volunteer.png',
              onTap: () {
                Navigator.push(
                    context,
                    MaterialPageRoute(
                        builder: (context) => BecomeVolunteer()));
              }),
        ],
      ),

Here donateDialog is another function which opens up a dialog.

void donateDiaolg() {
showDialog(..implementation..);}

So my doubt here is that should is use fat operator to call the donateDialog function or just call it like there in above code.

My basic question is should i use this

onTap: () => donateDialog(),

or this

onTap: donateDialog(),

or is it okay to do like this

onTap: donateDialog

It would be better if someone explains me these three function call.


Solution

  • It depends on function signature. for example onTap property needs function with no argument. if your custom function is same you can use your function name directly like onTap: myFunc. if your function's signature take 1 or more arguments you should pass empty function to onTap and call your function through it.