Flutter, onPressed: () {…}. 与 onPressed: methodCall() 之间的不同是什么?

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

Flutter, What is different between onPressed: () {...}. and onPressed: methodCall()

问题

我正在处理audio_service示例。

似乎,auidoHandler.play或暂停等调用只能像下面这样工作:

onPressed: auidoHandler.play

而不像这样:

onPressed : () -> {auidoHandler.play}

我没有时间去学习Dart或Flutter,但我必须这样做。

请给我一些启发。

英文:

I am working on audio_service example.

and I seems, auidoHandler.play or pause ..else callings work only like below

onPressed: auidoHandler.play 

not like

onPressed : () -> {auidoHandler.play}

I did not have time to learn about dart or flutter but i have to do.

Plese enlight me.

答案1

得分: 1

onPressed 需要提供一个函数的引用。auidoHandler.play 是一个函数,因此可以使用它。

() -> {auidoHandler.play} 也是一个函数,但是它什么都不做,因为它缺少在结尾的函数调用运算符 ()

应该是 () -> {auidoHandler.play();}

注意:
在你的问题标题中提到的选项 onPressed: methodCall() 不会起作用,因为 methodCall() 会在组件挂载时调用该函数,结果将作为事件调用的函数传递。除非函数返回另一个函数,否则这不会起作用。

英文:

onPressed needs to get provided a reference to a function. auidoHandler.play is a function thus it can be used.

() -> {auidoHandler.play} is also a function but a function that does nothing because its missing the function call operator () at the end.

It should be () -> {auidoHandler.play();}

Note:
The option stated in the title of your question onPressed: methodCall() would not work because the methodCall() would call the function when the component is mounted and the result whould be passed as the function to be called on the event. Unless the function returns another function this would not work.

答案2

得分: 0

以下是翻译好的部分:

onPressed: auidoHandler.play,

等同于

onPressed: () {
  auidoHandler.play();
},

onPressed: () => auidoHandler.play(),

实际上,第一个版本是代码检查工具(linter)首选的方式(参见unnecessary_lambdas)。


你的问题是在第二个示例中没有调用方法 auidoHandler.play

onPressed : () -> {auidoHandler.play}

替换为

onPressed: () {
  auidoHandler.play();
},

onPressed: () => auidoHandler.play(),
英文:
onPressed: auidoHandler.play,

is equivalent to

onPressed: () {
  auidoHandler.play();
},

or

onPressed: () => auidoHandler.play(),

In fact, the first version is preferred by the linter (see unnecessary_lambdas).


Your issue is that you are not calling the method auidoHandler.play in your second example:

Replace

onPressed : () -> {auidoHandler.play}

with

onPressed: () {
  auidoHandler.play();
},

or

onPressed: () => auidoHandler.play(),

huangapple
  • 本文由 发表于 2023年4月11日 09:52:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/75981880.html
匿名

发表评论

匿名网友

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

确定