How to pass callback in Flutter

This is a more general answer for future viewers.

Callback types

There are a few different types of predefined callbacks:

final VoidCallback myVoidCallback = () {};
final ValueGetter<int> myValueGetter = () => 42;
final ValueSetter<int> myValueSetter = (value) {};
final ValueChanged<int> myValueSetter = (value) {};

Notes:

  • VoidCallback is an anonymous function that takes no arguments and returns no value.
  • ValueGetter is an anonymous function that returns a value, which you provide for someone who wants to get it.
  • ValueSetter is an anonymous function that takes a value as an argument, which you can use to set some other value.
  • ValueChanged has the same function signature and is used the same way as ValueSetter, but its name emphasizes that the given value actually changed (and was not just set with the same value again).

See this answer for more details.

Ways to write the callback

Good

When you are asked to provide a callback to an API, you can directly write the callback:

onPressed: () {},

Or you can supply the callback variable name (without parentheses):

onPressed: myVoidCallback,

Less good

It would be unnecessarily verbose to use both forms (but you could if you included the parentheses after the variable name):

onPressed: () {
  myVoidCallback();
},

This one is equivalent (but also unnecessarily verbose):

onPressed: () => myVoidCallback(),

Just use one of the “Good” forms from above.

Still good

The exception would be if you wanted to do something like call a value setter when the parameter is only asking for a void callback:

onPressed: () => myValueSetter(42),

Leave a Comment

tech