Dart Anonymous Functions: Callback Functions
In Dart, anonymous functions play a crucial role in implementing callback functions. Callback functions are functions passed as arguments to other functions, and they get executed at a later time. This is a powerful concept, especially when dealing with asynchronous operations or events.
Example: Using Anonymous Functions as Callbacks:
void main() {
// Simulating an asynchronous operation with a delay
void fetchData(void Function(String) callback) {
// Simulating a delay of 2 seconds
Future.delayed(Duration(seconds: 2), () {
// Data fetched after the delay
String data = "Dart is awesome!";
// Calling the callback function with the fetched data
callback(data);
});
}
// Using an anonymous function as a callback
fetchData((result) {
print("Fetched Data: $result");
});
print("Fetching data..."); // Printed immediately, before the data is fetched
}
In this example, the fetchData
function takes a callback function as a parameter. Inside fetchData
, we simulate an asynchronous operation using Future.delayed
to represent fetching data after a delay. Once the data is ready, the callback function is executed with the fetched data.
The anonymous function (result) { print("Fetched Data: $result"); }
is passed as a callback to fetchData
. It gets executed when the data is ready, allowing us to handle the result.
Callbacks, along with anonymous functions, are powerful tools in Dart, particularly in scenarios where you need to manage asynchronous operations, events, or respond to certain conditions. They provide a flexible way to handle functionality that occurs at a later time in your program.