0

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.

sosnus
  • 968
  • 10
  • 28

2 Answers2

1

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.

Daniel Cruz
  • 1,437
  • 3
  • 5
  • 19
  • Why Google allow us to use 'play' with out (); ? Don't u think it must be a error? – RatpoisonManager Apr 11 '23 at 02:54
  • I agree. I didn't know it allowed that. As far as type checking goes I think flutter can't know that is invalid because both are functions and I think both return null. But I think `auidoHandler.play;` should not be a valid statement. I don't know under what conditions it could be used like that. – Daniel Cruz Apr 11 '23 at 19:27
0
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(),
Valentin Vignal
  • 6,151
  • 2
  • 33
  • 73