Call functions in a uncommon way with Function.apply() method

As a developer, “calling” or “executing” functions is the thing you do many times per your working day. It’s a common action. However, in this post, we will try an uncommon way to execute functions in Dart using static Function.apply() method.

1. Syntax

// Syntax

dynamic apply (
  Function function,
  List? positionalArguments,
  [Map<Symbol, dynamic>? namedArguments]
)
// Simple Example
void helloEcomobi() {
  print('Hello Ecomobi.');
}

void main() {
  Function.apply(helloEcomobi, [], {});
}

// Output
Hello Ecomobi.
  • function: The name of the function you want to execute (“helloEcomobi”).
  • positionalArguments: List of (both required and optional) positional arguments , wrapped in square brackets. In above example, there is no positional argument, therefore we provide empty list ([ ]).
  • namedArguments: Map of (optional) named arguments, wrapped in curly brackets. In above example, there is no named argument, therefore we provide empty map ({ }).
  • The return type of Function.apply() is the return type of the executed function. In above example, the return type is void.

2. Examples

2a. Execute function with optional named parameters

// Optional named parameters

void helloEcomobi1(int year, {String country, String city}) {
  print('Hello Ecomobi. $country, $city $year.');
}

void main() {
  Function.apply(helloEcomobi1, [2023], {#country: 'Vietnam', #city: 'Hanoi'});
}

// Output
Hello Ecomobi. Vietnam, Hanoi 2023.
  • Function helloEcomobi1 has one required positional parameter (year) and two optional named parameters. The “year” is in square brackets, country and city are in curly brackets.
  • Each optional named argument starts with a hash character (#)

2b. Execute function with optional positional parameters

// Optional positional parameters

void helloEcomobi2(int year, [String country, String city]) {
  print('Hello Ecomobi. $country, $city $year.');
}

void main() {
  Function.apply(helloEcomobi2, [2023, 'Vietnam', 'Hanoi']);
}

// Output
Hello Ecomobi. Vietnam, Hanoi 2023.
  • All positional parameters (both required and optional) are in the square brackets.

2c. Execute function with return value

// With return value

int sum(int a, int b) {
  return a + b;
}

void main() {
  int result = Function.apply(sum, [1, 2]);
  print('Sum = $result');
}

// Output
Sum = 3

Related Posts