Function as an argument in another function - Dart

4,918

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.

Share:
4,918
Yousef Gamal
Author by

Yousef Gamal

Updated on December 07, 2022

Comments

  • Yousef Gamal
    Yousef Gamal over 1 year

    What's the difference between

    void test1(void fun(String element)) {
      fun("Test1");
    }
    
    //AND
    
    void test2(Function(String element) fun) {
      fun("Test2");
    }
    

    I tried to run both of them and can't find any differences in the output:

    void main() {
      test1((test) => print(test));
      test2((test) => print(test));
    }
    
    void test1(void fun(String element)) {
      fun("Test1");
    }
    
    void test2(Function(String element) fun) {
      fun("Test2");
    }
    
    // Output:  
    // Test1   
    // Test2
    

    I'm new to Dart I've always been using Java, so passing function to a function is something new to me, so if someone can explain to me what's the differences in the above code would be very grateful.