Junior — Middle
How can an object of type Future be initialized in your programming language?
sobes.tech AI
Answer from AI
In Dart (Flutter language), an object of type Future can be initialized in several ways:
- Using the Future constructor with a function:
Future<String> future = Future(() {
// Some asynchronous operation
return "Result";
});
- Using Future.value to create an already completed Future:
Future<int> future = Future.value(42);
- Using an async function that automatically returns a Future:
Future<String> fetchData() async {
await Future.delayed(Duration(seconds: 1));
return "Data";
}
- Using Future.delayed for a delayed result:
Future<String> future = Future.delayed(Duration(seconds: 2), () => "Delayed result");
Thus, Future is an object that will contain the result of an asynchronous operation in the future.