Why onTap function runs without tapping when it have arguments?

389 Views Asked by At

I am novice in programming. My question why this function is called without tap when I use arguments?

String _gesture = 'No Gesture Detected';
  _printgesture(var gestureName) {
    setState(() {
      _gesture = gestureName;
      print("PRINTGESTURE FUNCTION CALLED");
    });
  }

InkWell(
       onTap: _printgesture('Tap Detected'),
       // onTap: () {
       //   _printgesture('Tap Detected');
       // },
       child: Icon(Icons.dangerous_rounded, size: 300),
),

I wrote it inside anonymous function, it worked though, but still I want to understand why it runs automatically.

3

There are 3 best solutions below

1
On BEST ANSWER

Change

onTap: _printgesture('Tap Detected'),

to

onTap: (){_printgesture('Tap Detected'),}

As onTap is of type GestureTapCallback function, When using on onTap: _printgesture('Tap Detected'), you are directly executing printgesture('Tap Detected') without waiting for the tap function to get pressed. So when you change it to (){_printgesture('Tap Detected') the function would get called only when tapped.

Refer: https://api.flutter.dev/flutter/gestures/GestureTapCallback.html

0
On
       onTap: () => _printgesture('Tap Detected'),

Try replacing this with your onTap function

1
On

When you write

onTap: _printgesture('Tap Detected'),

you are executing _printgesture right away and put the result of that function in the onTap parameter, which is null by the way, causing that the onTap doesn't even work.

I was actually surprised that it would compile at all but that's because you didn't define a return type for _printgesture. If you rightfully defined it as void _printgesture(var gestureName) { you will see that your code won't even compile.