Wed, Dec 7, 2022
Read in 2 minutes
In this post we learn what "async" keyword is in Dart.
In Dart, the async
keyword is used to define asynchronous functions. An asynchronous function is a function that can run concurrently with other parts of the program. Asynchronous functions are used to perform time-consuming operations, such as network requests, without blocking the user interface.
The async
keyword is used to mark a function as asynchronous. When a function is marked as async
, it can use the await
keyword to pause the function’s execution until a value is returned from an asynchronous operation.
Here’s an example of defining an asynchronous function:
Future<String> fetchUserData() async {
// Perform a network request to fetch user data
String data = await NetworkRequest('https://example.com/user-data').getData();
return data;
}
In this example, we define an asynchronous function called fetchUserData
. The function returns a Future
that contains a String
value. The async
keyword is used to mark the function as asynchronous. The await
keyword is used to pause the function’s execution until the NetworkRequest
object returns data.
The Future
class is used to represent a value that will be available in the future. The await
keyword is used to wait for the future to complete and return its value. When the value is returned, the function resumes execution.
Here’s an example of calling an asynchronous function:
void main() async {
String userData = await fetchUserData();
print(userData);
}
In this example, we call the fetchUserData
function using the await
keyword to wait for the function to complete and return its value. When the value is returned, it is assigned to the userData
variable, and the value is printed to the console.
The async
keyword can also be used with for
loops and while
loops to create asynchronous loops. Here’s an example:
Future<void> printNumbers() async {
for (int i = 0; i < 10; i++) {
await Future.delayed(Duration(seconds: 1));
print(i);
}
}
In this example, we define an asynchronous function called printNumbers
. The function uses a for
loop to print the numbers from 0 to 9, with a delay of one second between each number. The await
keyword is used to pause the loop’s execution until the delay is complete.
The async
keyword is an essential feature of Dart’s concurrency model. It allows developers to write efficient and responsive programs that can perform time-consuming operations without blocking the user interface.