Pass a typed function as a parameter in Dart
To strongly type a function in dart do the following:
- Write down the
Function
keyword
Function
- Prefix it with its return type (for example
void
)
void Function
- Append it with parentheses
void Function()
- Put comma separated arguments inside the parentheses
void Function(int, int)
- Optionally - give names to your arguments
void Function(int foo, int bar)
Real life example:
void doSomething(void Function(int arg) f) {
f(123);
}
Dart v1.23 added a new syntax for writing function types which also works in-line.
void doSomething(Function(int) f) {
f(123);
}
It has the advantage over the function-parameter syntax that you can also use it for variables or anywhere else you want to write a type.
void doSomething(Function(int) f) {
Function(int) g = f;
g(123);
}
var x = <int Function(int)>[];
int Function(int) returnsAFunction() => (int x) => x + 1;
int Function(int) Function() functionValue = returnsAFunction;
Edit: Note that this answer contains outdated information. See Irn's answer for more up-to-date information.
Just to expand on Randal's answer, your code might look something like:
typedef void IntegerArgument(int x);
void doSomething(IntegerArgument f) {
f(123);
}
Function<int>
seems like it would be a nice idea but the problem is that we might want to specify return type as well as the type of an arbitrary number of arguments.