Pass a typed function as a parameter in Dart

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;

Leave a Comment