调用不带括号的函数和带括号的函数有什么区别

时间:2019-12-27 07:48:36

标签: flutter dart

调用不带括号的函数和onPressed或Ontap上带括号的函数有什么区别?

我只知道不能在onPressed上用括号调用void函数。

floatingActionButton: FloatingActionButton(
    onPressed: _incrementCounter,
    tooltip: 'Increment',
    child: Icon(Icons.add),
  ),

_incrementCounter的返回类型无效

void _incrementCounter() {
    setState(() {
        _counter++;
    });  
}

但是我没有找到任何适当的文档。

6 个答案:

答案 0 :(得分:2)

_incrementCounter中的

onPressed是一个函数引用,基本上意味着它不会立即执行,而是在用户单击特定窗口小部件之后执行。(回调)

_incrementCounter()是一个函数调用,它会立即执行。

因此,在onPressed内,您可以传递函数引用或将用作回调的匿名函数。

floatingActionButton: FloatingActionButton(
    onPressed: _incrementCounter,
    tooltip: 'Increment',
    child: Icon(Icons.add),
  ),

floatingActionButton: FloatingActionButton(
    onPressed: () {
        // Add your onPressed code here!
      },
    tooltip: 'Increment',
    child: Icon(Icons.add),
  ),

这不是飞镖特有的东西,它也可以用javascript和许多其他语言来完成:

What is the difference between a function call and function reference?

Javascript function call with/without parentheses

答案 1 :(得分:1)

incrementCounter是对该函数的引用。您将把函数作为参数传递,以便稍后在某处调用。如果您有子小部件,通常将其用作回调函数

incrementCounter()将调用函数调用。在这种情况下,您不想创建小部件时计数器将自动加1。

通常直接调用该函数是不合适的,您应该这样编写:

protected function prepareForValidation()
{
    $this->request->merge([
        'city' =>  explode('/', $this->request->get('citytown'))[0],
        'town' =>  explode('/', $this->request->get('citytown'))[1]
    ]);
}

OR

onPressed: () {
   _incrementCounter();
},

答案 2 :(得分:1)

这里是区别:

onPressed:_incrementCounter 是对现有函数的引用。

仅当 onPressed _incrementCounter 所需的回调参数兼容时,此选项才有效。

onPressed:_incrementCounter()已执行_incrementCounter(),并将返回的结果传递给 onPressed 。这是一个普遍的错误,当您无意中执行此操作时实际上是要传递对 _incrementCounter 的引用而不是调用它。

答案 3 :(得分:0)

void _incrementCounter() {
    setState(() {
        _counter++;
    });  
}    

floatingActionButton: FloatingActionButton(
    onPressed: _incrementCounter,
    tooltip: 'Increment',
    child: Icon(Icons.add),
  ),

*正如我所看到的,在您的代码中,该函数的返回类型无效。在flutter中,如果返回类型为void并且该函数在同一个类中定义,则在小部件中调用已定义的函数,则我们不使用括号。在混乱中,我们只需使用括号......即可调用该函数……最终将充当指针,该指针将指向返回类型为void且在与在小部件中调用函数的同一类中定义的函数*

答案 4 :(得分:0)

简单地说,在 onPressed 中,我们可以传递像函数引用或匿名函数这样的回调函数,因此当用户单击此特定小部件时,该函数将引用并执行,但通常在构建该特定小部件时会直接执行带括号的函数。< /strong>

答案 5 :(得分:-1)

使用括号表示您要给函数提供一组空参数以运行。如果函数需要0个参数,则在函数名称中使用括号将执行该函数。

另一方面,没有参数意味着您只是在提到该功能。喜欢,

8;//Here I'm just mentioning 8. It's useless

示例:

void fun(){
  print('Func is running!');
}

void main(){
func();//Here i wanna execute 'func'
Function a = func;//Here i wanna assign 'func' to a
}

输出:

功能正在执行