There are three keywords future, await, async to achieve asynchronous programming in Dart. I found the below example from the official documentation is most insightfull.
Future printOrderMessage() async { print('Awaiting user order…'); var order = await fetchUserOrder(); print('Your order is: $order'); }
Future fetchUserOrder() { // Imagine that this function is more complex and slow. return Future.delayed(Duration(seconds: 4), () => 'Large Latte'); }
Future main() async { countSeconds(4); await printOrderMessage(); }
// You can ignore this function - it's here to visualize delay time in this example. void countSeconds(int s) { for (var i = 1; i <= s; i++) { Future.delayed(Duration(seconds: i), () => print(i)); } }
In main, countSeconds run right away. It is an “asynchronous” function achived by the future keywords. Note that the program immediately returns from countSeconds and continue to run printOrderMessage even though the former is not “completed”. The future keyword essentially indicates the compiler should implement a thread for countSeconds and return values in future times.
As for the keyword await, it simply indicates to the compiler that we should wait for the current result to continue. And whenever we have the await keyword in a function, we have to add async at the beginning of the function. Moreover, we should only await a future function. For example, we may define printOrderMessage as void. But we will get warning message.