— Dart, Flutter, Function Passing, Callbacks — 1 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.
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.
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:
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 usage10 }11}
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 usage8 }9}
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 @override7 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.