returning futures
Future<void> main() async {
printCountdown();
print("${await delayedGreeting()}");
}
Future<String> delayedGreeting() {
return Future.delayed(Duration(seconds: 10), () => "Thank you for waiting 10 seconds");
}
void printCountdown() {
for (int i = 1; i <= 10; i++) {
Future.delayed(Duration(seconds: i), () {
print(i);
});
}
}
Here, printCountdown
enters 10 Future entries to the event loop, each setting of at different seconds (1, 2, 3, 4 ... 10). You could think the entry of these Futures as instantaneous. This is one way to use Future.delayed. But another one is in delayedGreeting
. Notably, here we are able to return the result of the function passed to Future.delayed
as if it came from delayedGreeting
. Note that delayedGreeting
returns the Future.delayed
as it is.