Function as an argument in another function - Dart Function as an argument in another function - Dart dart dart

Function as an argument in another function - Dart


There is no real difference between declaring a function parameter with a function type preceding the name (void Function(String) fun), or as a (C-like) function-like syntax where the name is in the middle (void fun(String element)). Both declare an argument named fun with type void Function(String).

Dart didn't originally have a way to write a function type in-line, you had to use a typedef, so most older code uses the void fun(String element) notation. When the returnType Function(arguments) notation was introduced (because it was needed for specifying generic function types), it became easier to write function typed parameters with the type first.

Both are being used, neither is idiomatic, use whatever you think reads best.

There is one difference between the two formats that are worth remembering:

  • The void fun(String element) notation requires names for the function arguments. If you write void fun(String) it is interpreted as a function taking one argument of type dynamic with the name String.
  • The void Function(String) fun notation assumes that a single argument name is the type.

I personally prefer the original function parameter format, except for having to write the argument names.