1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
int milk = 0; String? createDrink() { if (milk == 0) { throw Exception ("out of milk"); } if (milk > 4) { milk = milk - 4; return 'Cappicino'; } } Future <String?> fetchUserOrder() => Future.delayed( Duration(seconds:2), () => createDrink() ); |
1 2 3 4 5 6 7 8 9 10 11 12 13 |
Future <void> main() async { try { final order = await fetchUserOrder(); // if there is an exception, // next lines will not be executed. // however, if no exception, then we simply continue processing future statements. print(order); } catch (e) { print(e); } finally { print('...Done....'); } } |
- Use await to wait until a Future completes
- Use multiple awaits to run Futures in sequences
- await is only allowed inside async functions
- use try/catch to handle exceptions
- async/await + try/catch is a great way of working with Futures in Dart
Another Example
1 2 3 4 5 6 7 8 9 |
Future <void> main() async { print('-- start --'); for (var i = 10; i >=0; i--) { // wait for each delay to finish before starting on the next one. await Future.delayed( Duration(seconds:1), () => print(i), ); } |