Flutter pass future function as parameter

In Flutter, you can pass a future function as a parameter to another function or widget. This allows you to create more flexible and dynamic code by delaying the execution of a function until a future completes.

Here is an example of how to pass a future function as a parameter in Flutter:


Future<String> fetchData() async {
// Some asynchronous data fetching
await Future.delayed(Duration(seconds: 2)); // Simulating delay
return "Data from fetch";
}

void executeFunction(Future<String> Function() futureFunction) async {
String data = await futureFunction();
print(data);
}

void main() {
executeFunction(fetchData);
}

In this example, we have a function called fetchData() that returns a future of type String. This function simulates fetching data asynchronously by delaying for 2 seconds and then returning a dummy data string.

We also have a function called executeFunction() that accepts a future function as a parameter. Inside this function, we await the execution of the future function and print the returned data.

Finally, in the main() function, we pass fetchData (without parentheses) as an argument to executeFunction(). This effectively passes the fetchData function as a parameter to executeFunction() to be executed later.

When you run this code, you will see that “Data from fetch” is printed after a 2-second delay, indicating that the fetchData() function was successfully passed as a parameter to executeFunction() and executed as a future function.

Leave a comment