Dart 中 onPressed 属性后面的空括号是什么意思? [英] What does the empty parentheses after the onPressed property mean in Dart?
问题描述
我知道在小部件的 onPressed
和 onTap
之后调用函数的语法.有两个选项我们可以使用 () =>function()
或 () { function();}
语法.空括号是什么意思?
I know the syntax for calling a function after onPressed
and onTap
for a widget. There are two options We can use either the () => function()
or the () { function(); }
syntax. What do the empty parentheses mean?
推荐答案
() =>表达式
或 () { statements }
创建一个闭包或内联函数.
() => expression
or () { statements }
creates a closure or inline function.
通过这种方式,您可以创建内联函数,该函数作为参数传递,以便在您传递给它的小部件发生 onPressed
事件时调用.
This way you create inline a function that is passed as argument to be called in case of the event onPressed
by the widget you pass it to.
expression
或 statements
具有创建它们的可用上下文,并且可以访问和使用该上下文中可用的所有成员和标识符(变量、方法、函数、类型定义, ...).
The expression
or statements
have the context where they were created available and can access and use all members and identifiers available in that context (variables, methods, functions, typedefs, ...).
如果你使用
onPressed: myFunction
传递对现有函数的引用.
这仅在onPressed
和myFunction
预期的回调参数兼容时才有效.onPressed: myFunction()
myFunction()
被执行并将返回的结果传递给onPressed
.这是一个常见的错误,在无意中执行时实际上是为了传递对myFunction
的引用而不是调用它.
onPressed: myFunction
a reference to an existing function is passed.
This only works if the parameters of the callback expected byonPressed
andmyFunction
are compatible.onPressed: myFunction()
myFunction()
is executed and the returned result is passed toonPressed
. This is a common mistake when done unintentionally when actually the intention was to pass a reference tomyFunction
instead of calling it.
这篇关于Dart 中 onPressed 属性后面的空括号是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!