Dart 中 onPressed 属性后面的空括号是什么意思? [英] What does the empty parentheses after the onPressed property mean in Dart?

查看:18
本文介绍了Dart 中 onPressed 属性后面的空括号是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道在小部件的 onPressedonTap 之后调用函数的语法.有两个选项我们可以使用 () =>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.

expressionstatements 具有创建它们的可用上下文,并且可以访问和使用该上下文中可用的所有成员和标识符(变量、方法、函数、类型定义, ...).

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 传递对现有函数的引用.
    这仅在 onPressedmyFunction 预期的回调参数兼容时才有效.
  • 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 by onPressed and myFunction are compatible.
  • onPressed: myFunction() myFunction() is executed and the returned result is passed to onPressed. This is a common mistake when done unintentionally when actually the intention was to pass a reference to myFunction instead of calling it.

这篇关于Dart 中 onPressed 属性后面的空括号是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆