How to declare async function as a variable in Dart?

In Dart, you can declare an asynchronous function as a variable using the Future or Function type. Both approaches allow you to store and call asynchronous functions using the variable name.

  1. Using Future Type: You can declare an async function as a variable with the Future type. The Future type represents a potential value or error that will be available at some time in the future. An async function in Dart returns a Future, so you can assign it to a variable of type Future.
Future<int> fetchSomeData() async {
  // Simulate an asynchronous operation.
  await Future.delayed(Duration(seconds: 2));
  return 42;
}

void main() {
  // Declare an asynchronous function as a variable of type Future.
  Future<int> Function() asyncFunction = fetchSomeData;

  // Call the async function using the variable.
  asyncFunction().then((result) {
    print('Result: $result');
  });
}

In this example, we declare asyncFunction as a variable of type Future<int> Function(). We then assign the fetchSomeData function (which is an asynchronous function that returns a Future<int>) to the asyncFunction variable. Finally, we call the function using the variable and handle the result using the then method.

  1. Using Function Type: You can also declare an async function as a variable using the Function type. The Function type is a generic type that allows you to specify the function’s return type and parameter types. This approach is more generic but less type-safe compared to using the Future type.
Future<int> fetchSomeData() async {
  // Simulate an asynchronous operation.
  await Future.delayed(Duration(seconds: 2));
  return 42;
}

void main() {
  // Declare an asynchronous function as a variable of type Function.
  Function asyncFunction = fetchSomeData;

  // Call the async function using the variable.
  asyncFunction().then((result) {
    print('Result: $result');
  });
}

In this example, we declare asyncFunction as a variable of type Function. The variable can hold any function, including asynchronous ones. It is less specific about the function’s return type and parameters compared to using the Future type.

It’s worth noting that using the Function type is more flexible but may lead to runtime errors if you try to call the function with the wrong number or types of arguments. Therefore, using the Future type is generally safer and more explicit when dealing with asynchronous functions that return futures.

error: Content is protected !!