Sobes.tech
Junior — Middle

Can you explain what a Future object is and how it is used in asynchronous programming?

sobes.tech AI

Answer from AI

A Future object in asynchronous programming represents a promise to obtain the result of an operation in the future, once it completes.

In Flutter (and Dart), Future is used for working with operations that execute asynchronously, such as network data loading or file reading. Instead of blocking execution, the program continues working, and when the Future completes, the result or error can be processed.

Example of using Future in Dart:

Future<String> fetchData() async {
  // simulate delay, e.g., network request
  await Future.delayed(Duration(seconds: 2));
  return 'Data loaded';
}

void main() async {
  print('Starting load');
  String data = await fetchData();
  print(data); // Will print: Data loaded
}

Here, fetchData returns a Future<String> that completes after 2 seconds. The await keyword allows waiting for the result without blocking the main thread.

Can you explain what a Future object is and how it is… - sobes.tech