Junior — Middle
How can small tasks be executed within asynchronous processing?
sobes.tech AI
Answer from AI
In Flutter, to perform small asynchronous tasks, Future and async/await are usually used. This allows not to block the main UI thread and to perform operations like data loading or calculations in the background.
Example of an asynchronous function that performs a task with a delay:
Future<String> fetchData() async {
await Future.delayed(Duration(seconds: 2)); // simulate a long operation
return 'Data loaded';
}
void main() async {
print('Starting load');
String result = await fetchData();
print(result);
}
If you need to perform several tasks in parallel, you can use Future.wait:
Future<void> performTasks() async {
var results = await Future.wait([
task1(),
task2(),
]);
print(results);
}
For more complex asynchronous processing, Stream or isolates (Isolate) can be used, but for small tasks, Future and async/await are usually sufficient. This allows writing clear and efficient asynchronous code.