Blog

[Flutter] Understanding async method code

Published 1 min read

Future<String> createOrderMessage() async { var order = await fetchUserOrder(); return 'Your order is: $order'; } Future<String> fetchUserOrder() { return Future.delayed( Duration(seconds: 2), () => 'Large Latte', ); } void main() { print(createOrderMessage()); }
Instance of '_Future<String>' // Output

Let's see why it prints this.
main method calls createOrderMessage(), and when the called method hits await,
it first returns a Future<String> with no String.
Then main method should wait until the String is delivered to the Future,
but the createOrderMessage() method is waiting for 2 seconds at await fetchUserOrder().

main method didn't use await when calling the createOrderMessage() method,
so it went straight to print(), and
an empty Future<String> object was returned.

The fix is to make main method an async method too, and use await
when calling createOrderMessage().

Comments

Leaving a comment stores your nickname (or GitHub profile info). Privacy policy

GitHub