Skip to content
DeveloperMemos

Passing Functions with Parameters in Dart

Dart, Flutter, Function Passing, Callbacks1 min read

In Dart, a common requirement is to pass functions as parameters to other functions or constructors. This is particularly useful in Flutter for handling events like button presses or other user interactions. However, when these functions need to accept parameters, you cannot directly use a VoidCallback. This article explains how to pass functions with parameters in Dart, with practical examples.

Understanding VoidCallback

A VoidCallback is a function type in Dart that takes no parameters and returns no value. It's defined as:

1typedef void VoidCallback();

This is suitable for simple callbacks that do not require any argument. However, for more complex interactions where you need to pass arguments, you need a different approach.

Passing Functions with Parameters

To pass a function that accepts parameters, you can define a custom function type or use inline function types. Here are two methods to achieve this:

Method 1: Using Custom Typedef

Define a custom function type using typedef. This is useful for readability and reusability.

1typedef MyCallback = void Function(int value);
2
3class MyOtherClass {
4 final MyCallback callback;
5
6 MyOtherClass(this.callback);
7
8 void executeCallback() {
9 callback(5); // Example usage
10 }
11}

Method 2: Inline Function Type

You can directly specify the function type inline without using typedef.

1class MyOtherClass {
2 final void Function(int) callback;
3
4 MyOtherClass(this.callback);
5
6 void executeCallback() {
7 callback(5); // Example usage
8 }
9}

Example Usage

Here's an example of how you might use these in a real-world scenario, such as in a Flutter widget.

1class MyWidget extends StatelessWidget {
2 final MyCallback onButtonPressed;
3
4 const MyWidget({required this.onButtonPressed});
5
6 @override
7 Widget build(BuildContext context) {
8 return TextButton(
9 onPressed: () => onButtonPressed(10),
10 child: Text('Press Me'),
11 );
12 }
13}

In the above example, onButtonPressed is a callback that accepts an integer. When the button is pressed, it triggers this callback with the specified value.