Dart| Flutter How to: Function Return a function

This tutorial shows multiple ways to execute a function repeatedly with a delay timer in dart and flutter programming.

Functions declare a return type and return values.

In Dart Function also returns functions, which means Function is also typing like primitive type. And type is Function.

How to Return a function in Dart

The below examples show that Functions return the Function type.

Function Declaration contains Return type as Function.

Function FuncationName(arguments);

Function Body contains a closure function that returns the function name. Nested Function Return:

Here is an Example Functions returns Function type

void main() {
  Function sumCalculator = calculator(1);
  print(sumCalculator(6)); //7
  print(calculator(20)(5)); //25
}

Function calculator(int first) {
  num sum(second) {
    return first + second;
  }

  return sum;
}

Output:

7
25

The same can be rewritten using Arrow or an anonymous Function Arrow Function Return:

void main() {
  Function sum = calculator(8);
  print(sum(4)); //12
  print(calculator(2)(6)); //8
}

Function calculator(int first) {
    return (second) => first + second;
}

Output:

12
8

Here is another function declaration with Function()

In this, It returns functions without names ie. values also called function literal.

Function literal Syntax:

In this Function, declaration is added with Function()

  • Nested function has no name
  • Return the function literals
  • Function is assigned to variable of Type Function
void main() {
  Function function = getMessage();
  print(function());
}

String Function() getMessage() {
  return () {
    return 'Hi John';
  };
}

Conclusion

To summarize, Learned multiple ways to return Functions with literal syntax, nested functions, and arrow functions.