为什么 `onTap` 函数在有参数的情况下在没有触摸时运行?

huangapple go评论60阅读模式
英文:

Why onTap function runs without tapping when it have 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 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.

答案1

得分: 2

更改

onTap: _printgesture('Tap Detected'),

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

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

答案2

得分: 0

onTap: () => _printgesture('Tap Detected'),
英文:
       onTap: () => _printgesture('Tap Detected'),

Try replacing this with your onTap function

答案3

得分: 0

当你写下

onTap: _printgesture('检测到点击'),

你立即执行了 _printgesture 并将该函数的结果放入了 onTap 参数中,而该参数默认是 null,导致 onTap 甚至无法工作。

我实际上很惊讶它能够编译通过,但这是因为你没有为 _printgesture 定义返回类型。如果你正确地将其定义为 void _printgesture(var gestureName) {,你将看到你的代码甚至无法编译。

英文:

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.

huangapple
  • 本文由 发表于 2023年3月1日 15:21:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/75600597.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定