Junior — Middle
How can asynchronous operations be used in the Dart language?
sobes.tech AI
Answer from AI
In Dart language, asynchronous operations are implemented using the keywords async and await, as well as through objects of type Future. This allows writing asynchronous code that looks like synchronous, simplifying reading and maintenance.
Example of using an asynchronous function:
Future<String> fetchData() async {
// simulate delay, e.g., a server request
await Future.delayed(Duration(seconds: 2));
return 'Data loaded';
}
void main() async {
print('Starting download');
String result = await fetchData();
print(result);
}
Here, fetchData returns a Future<String>, and await pauses the execution of the main function until the result is received. This allows not blocking the main thread and efficiently working with input-output operations, network requests, and other long-running tasks.