{

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 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 name 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.

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.





Related posts

Dart| Flutter How to: Read pubspec.yaml attributes (version) with examples

How to Create and build a Singleton Class Dart or Flutter example| Dart By Example

What is the difference between var and dynamic and final in dart?| Flutter By Example

How to: Check if Phone number is valid or not in Dart| Flutter By Example

Dart| Flutter How to read an image from a disk and resize a file

Dart/Flutter: How to write setter and getter fields or members variables in a class with Example

Dart| Flutter How to get extension name and MIME type of a file with example