Passing a Function as an Argument — Flutter💙

Dedan Ndungu
2 min readJan 8, 2022

--

Ever wondered how to pass a function as an argument. Or even better, Do you need to pass it so your code can remain clean and readable while maintaining the functionality.

If so let's dive in.

Photo by Christina @ wocintechchat.com on Unsplash

Flutter offers various ways to easily pass functions as arguments with most achieving more of like the same thing. This article aims to discuss them and add them to your canoe of knowledge 😁

1. Function() && Function(String val)

This is the most basic and where all the others base their implementation. You have the option to pass in a value with its variant Function(String val) which lets you receive the passed value in the callback function.

2. VoidCallback

As the name suggests, It lets you declare a function callback that does not pass in any value. It just listens for click events and passes them on like Function() above.

3. GestureTapCallback

One of the callbacks provided by the flutter framework that listens for tap events on the GestureDetector widget. Others provided are GestureDoubleTapCallback, GestureTapDownCallback, GestureTapCancelCallback etc.

4. ValueChanged && ValueSetter && ValueGetter

ValueChanged — Used when listening for a value change.

ValueSetter — Has the same signature as ValueChanged but is called even when the value hasn`t changed. It has an asynchronous counterpart AsyncValueSetter,

ValueGetter — It listens for events and is invoked on demand. It has an asynchronous counterpart AsyncValueGetter

Caution ⚠ 💀

As you have noticed the callbacks do not have brackets ( ) when being assigned. This is because if you add them, the function is executed by the build method during the Widget layout. Furthermore, it doesn`t listen to events afterwards thus the callback is not executed on a click event.

DO 🟢

ElevatedButton(onPressed: onTap, child: Text('Tap Me')),

DON`T 🔴

ElevatedButton(onPressed: onTap(), child: Text('Tap Me')),

UPDATE: Tear Offs

Since Flutter 2.5: the concept, Tear Off has been embraced.

It is simply passing a function as a parameter without calling it so the underlying Widget can use it later as shown below. Though you have been doing it in the past previous examples, it's nice to give the concept a name😁.

ElevatedButton(onPressed: onTap, child: Text('Tap Me')),

You can check out this video for more info on TearOffs

That`s all for Today people Adios Muchachos 👋👋

--

--

Dedan Ndungu

Senior Mobile Engineer || Flutter Enthusiast || Technical Writer