0

In the async codelab: Ref: https://dart.dev/codelabs/async-await

They have the following snippet:

Future<void> printOrderMessage() async {
  print('Awaiting user order...');
  var order = await fetchUserOrder();
  print('Your order is: $order');
}

Future<String> fetchUserOrder() {
  // Imagine that this function is more complex and slow.
  return Future.delayed(const Duration(seconds: 4), () => 'Large Latte');
}

void main() async {
  countSeconds(4);
  await printOrderMessage();
}

Based on the logic of printOrderMessage() I've made a similar function:

void main() async {
  int? value;
  value = await test();
  print(value);
}

Future<int?> test() async{
  print('Function has started');
  Future.delayed(Duration(milliseconds: 2000), () {
    return 4;
  });
}

In my case, it prints Function has started null. why doesn't it wait for the value to be populated

1
  • 2
    Because you don't return the inner future, so you await on nothing. return Future.delayed(Duration(milliseconds: 2000), () { <- add return first here Commented Oct 28, 2022 at 14:05

1 Answer 1

1
Future<int?> test() async {
  print('Function has started');
  await Future.delayed(Duration(milliseconds: 2000), () {});
  return 4;
}
Future<int?> test() async {
  print('Function has started');
  return Future.delayed(Duration(milliseconds: 2000), () {
return 4;
});
 
}
Sign up to request clarification or add additional context in comments.

1 Comment

you can remove "?" to int too

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.