Member-only story
Asynchronous programming in Flutter
In Flutter, the term “async” is used to mark a function as asynchronous. An asynchronous function is one that can perform time-consuming operations without blocking the execution of the program. It allows you to write code that can handle tasks such as network requests, file I/O, or database operations without freezing the user interface.
When a function is declared as asynchronous using the “async” keyword, it can use the “await” keyword to pause its execution until a particular operation completes. The “await” keyword can only be used within an asynchronous function and is followed by a Future or Stream object. The function will resume its execution once the awaited operation is finished, and it will return the value wrapped in a Future object.
Here’s an example to illustrate the usage of async and await in Flutter:
Future<void> fetchData() async {
print("Fetching data...");
// Simulating a network request that takes some time
await Future.delayed(Duration(seconds: 2));
print("Data fetched!");
}
void main() {
print("Start");
fetchData().then((_) {
print("Process fetched data");
});
print("End");
}
In this example, we have an asynchronous function fetchData()
. It uses the await
keyword to pause its execution for 2 seconds, simulating a network request. The function returns a…