Search code examples
flutterdartanonymous-functiongesturedetectorontap

Why onTap function runs without tapping when it have arguments?


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.


Solution

  • 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