14. Flutter Tutorial for Beginners – Future, Async and Await in Flutter

0
817

Async means that this function is asynchronous and you might need to wait a bit to get its result.

Await literally means – wait here until this function is finished and you will get its return value.

Future is a type that ‘comes from the future’ and returns value from your asynchronous function. It can complete with success(.then) or with an error(.catchError).

void main() async {
  await waitForMe();
  print('I was waiting here :)');
}
Future waitForMe() async {
  print('Started.');
  return Future.delayed(Duration(seconds: 5), () {
    print("Now I'm done!");
  });
}

Output is:

I/flutter ( 4115): Started.
I/flutter ( 4115): Now I'm done!
I/flutter ( 4115): I was waiting here :)

When you use await, your program will wait there until async function finishes. Use .then() if you don’t want to wait.

The following example in where we do not want to wait:

void main() async {
  waitForMe().then((_) {
    print("I'm more done THEN you :)");
  });
  print('I was waiting here :)');
}
Future waitForMe() async {
  print('Started.');
  return Future.delayed(Duration(seconds: 3), () {
    print("Now I'm done!");
  });
}

Output is:

I/flutter ( 5532): Started.
I/flutter ( 5532): I was waiting here :)
I/flutter ( 5532): Now I'm done!
I/flutter ( 5532): I'm more done THEN you :)

LEAVE A REPLY

Please enter your comment!
Please enter your name here