Junior — Middle
What is the purpose of the Future object and how is it used in asynchronous programming?
sobes.tech AI
Answer from AI
The Future object in asynchronous programming in Flutter (and Dart) represents a promise to obtain the result of an operation in the future. It is used for working with tasks that execute asynchronously, such as loading data from a network or reading a file.
Future allows:
- Starting an operation without blocking the main thread.
- Subscribing to the result using methods like
then(),catchError(),whenComplete(). - Using the
awaitkeyword for convenient asynchronous code syntax.
Example of usage:
Future<String> fetchData() async {
// Simulate delay
await Future.delayed(Duration(seconds: 2));
return 'Data loaded';
}
void main() async {
print('Starting download');
String data = await fetchData();
print(data);
}
Here, fetchData returns a Future<String> that completes after 2 seconds, after which the result can be obtained using await.