Asynchronous Processing in Dart and Flutter - Part Three - Async and Await

Asynchronous Processing, Dart, Google Flutter -

Asynchronous Processing in Dart and Flutter - Part Three - Async and Await

Async

When an async method is called, a Future is immediately returned, and the body of the method is executed later. Later on, as the body of the async function is executed, the Future returned by the function call will be completed along with its result. At the end of the async method, the value (from the completed Future) can be returned.

Await

Await expressions are used in async methods. They enable you to invoke asynchronous code (that returns a Future). Once the asynchronous code is invoked, the currently running function is suspended until the Future has completed or there is an Error or Exception.

Lets Run Some Code

Go to your web-browser and navigate here: https://dartpad.dartlang.org. Paste the following code into the code area on the left-side:


import 'dart:async';

String countUp(int count) {
  print('start count up');
  StringBuffer sb = new StringBuffer();
  for (int i = 0; i < count; i++) {
    sb.write(" ${i}");
  }
  print('finish count up');
  return sb.toString();
}

Future createFutureCounter(int count) {
  return new Future(() {
    return countUp(count);
  });
}

void countUpAsynchronously(int count) async {
  print('Async operation start');
  String value = await createFutureCounter(count);
  print('Async operation succeeded: ${value}');
}

void main() {
  print('start main');
  countUpAsynchronously(100);
  print('finish main');

Now hit the blue 'Run' button at the top and the following results should appear on the right side:

start main
Async operation start
finish main
start count up
finish count up
Async operation succeeded:  0 1 2 ... 97 98 99

What Happens When You Run the Code

  • The ‘main’ method is short-lived. It calls ‘countUpAsynchronously’ and exits.
  • The ‘countUpAsynchronously’ method is an async method. That means a Future is immediately returned and the body of the method is executed later. The body of the method is executed after the main completes and it invokes the ‘createFutureCounter’ and waits for it to finish. Once its finished it prints out the counts.
  • The ‘createFutureCounter’ method is called by the main and returns a new Future object containing a lambda which is executed asynchronously, calling the ‘countUp’ method.

Now Lets Add Some Error Handling

Stay on dartpad. Paste the following code into the code area on the left-side:


import 'dart:async';

String countUp(int count) {
  print('start count up');
  StringBuffer sb = new StringBuffer();
  for (int i = 0; i < count; i++) {
    if (i > 500) {
      throw new Exception("Over 500 not allowed.");
    }
    sb.write(" ${i}");
  }
  print('finish count up');
  return sb.toString();
}

Future createFutureCounter(int count) {
  return new Future(() {
    return countUp(count);
  });
}

void countUpAsynchronously(int count) async {
  print('Async operation start');
  String value;
  try {
    value = await createFutureCounter(count);
    print('Async operation succeeded: ${value}');
  } catch (ex) {
    print('Async operation errored: ${ex}');
  }
}

void main() {
  print('start main');
  countUpAsynchronously(1000);
  print('finish main');
}

Now hit the blue 'Run' button at the top and the following results should appear on the right side:

start main
Async operation start
finish main
start count up
Async operation errored: Exception: Over 500 not allowed.

What Happens When You Run the Code

  • The ‘main’ method is short-lived. It calls ‘countUpAsynchronously’ and exits.
  • The ‘countUpAsynchronously’ method is an async method. That means a Future is immediately returned and the body of the method is executed later. Later, the body of the method is executed, and it invokes the ‘createFutureCounter’ method.
  • The ‘createFutureCounter’ method returns a new Future object containing a lambda which is executed asynchronously, calling the ‘countUp’ method, which throws the Exception. That exception is then caught by method ‘countUpAsynchronously’ and the exception is printed out.