Junior — Middle
How does Dart implement the execution of asynchronous tasks and how does it affect the program's operation?
sobes.tech AI
Answer from AI
Dart implements asynchronous task execution using the keywords async and await, as well as through Future and Stream objects.
Futurerepresents a promise to obtain a result later, after an asynchronous operation completes.asyncmarks a function as asynchronous, allowing the use ofawaitinside it to wait for aFutureresult without blocking the main thread.
This enables the program not to block the user interface or the main execution thread, improving application responsiveness.
Example:
Future<String> fetchData() async {
// simulate delay
await Future.delayed(Duration(seconds: 2));
return 'Data loaded';
}
void main() async {
print('Starting load');
String data = await fetchData();
print(data);
}
In this example, the program does not block while waiting for data, which is important for smooth UI operation in Flutter.