Junior — Middle
Can you explain the principle of the Future object and how it is used in asynchronous programming?
sobes.tech AI
Answer from AI
The Future object in Flutter represents the result of an asynchronous operation that may be available in the future. It allows performing tasks without blocking the main thread and obtaining the result when the operation completes.
Principle of operation:
- You initiate an asynchronous function that returns a Future.
- The program continues to run without waiting for the operation to finish.
- When the operation completes, the Future is completed with a result or an error.
- You can handle the result using
then(),catchError(), or useasync/awaitfor more convenient syntax.
Example of usage:
Future<String> fetchData() async {
await Future.delayed(Duration(seconds: 2));
return 'Data loaded';
}
void main() async {
print('Starting download');
String data = await fetchData();
print(data);
}
In this example, fetchData returns a Future that will complete after 2 seconds with a result. The key advantage of Future is the ability to write asynchronous code that looks like synchronous code, improving readability and responsiveness of the application.