Asynchronous programming in Dart with examples

Asynchronous programming in dart :

Asynchronous programming runs in a separate thread. It can execute without blocking the main thread i.e. the application can keep working while the asynchronous code runs in the background. For example, if the application is downloading some data over the network, that part we can put in a asynchronous block.

The opposite of asynchronous is called synchronous. Synchronous code block waits for that execution to complete before movind to the next line.

For example

A
synchronous-block
B

Here, A will run, then synchronous-block will run and B will run. But B will wait for the synchronous-block to complete the execution time. Suppose it is reading contents of a file and it takes 20 seconds. The application will freeze for 20 seconds and that will not be a good user experience.

We can replace the synchronous-block with an asynchronous block and that will run in a different thread. No matter how much time it will take, our application will not freeze.

Example of Future :

Dart provides one class called Future to handle asynchronous programming. A Future object holds the result of a future task or a task that is running and it will complete in future. It will get either a success value i.e. the final result or an error. We can get each one of them in separate callback methods.

main(List<string> args) {
  print("--start--");
  Future<string> futureData = getFutureString();
  futureData.then((str) => print(str)).catchError((err) => print(err));
  print("--end--");
}
Future<string> getFutureString() {
  return Future.delayed(Duration(seconds: 4), () {
    return "Hello after 4 seconds";
  });
}

It will print the below output :

--start--
--end--
Hello after 4 seconds
  • Future instance produces a value of type T.

  • If the function doesn’t have any return type, change it to Future.

  • getFutureString returns one string after four seconds. It’s return type is Future i.e. a Future object.

  • In the main method, futureData variable holds that Future returned value.

  • We are using then-catchError on futureData.

  • The then block will be called once we get one value from the Future object and catchError block will be called if we get one error.

  • The main method starts and ends without waiting for the Future to complets. The program receives the string inside then block and prints it out.

Example of Future with an error :

Change the getFutureString method of the above example as like below :

Future<string> getFutureString() {
  return Future.delayed(Duration(seconds: 4), () {
    throw Exception('Delayed exception !');
  });
}

Now, it will print :

--start--
--end--
Exception: Delayed exception !

This time, it executes the catchError block.

async and await :

In the above example, we received the Future value inside then and catchError block. Dart provides two more keywords to handle asynchronous programming. These are called async and await.

async is used to declare one asynchronous function. This keyword is used just before the function body. await is used with function call to wait for a function to complete.

main(List<string> args) {
  print("--start--");
  getData();
  print("--end--");
}
getData() async {
  print("Getting data..");
  var futureData = await getFutureString();
  print("Result : $futureData");
}
Future<string> getFutureString() async {
  return Future.delayed(Duration(seconds: 5), () {
    return "Hello after 5 seconds from a async function";
  });
}
  • getFutureString is an async function.

  • getData is also an async function. Inside this function, we are using await to get the result from getFutureString.

  • We are storing the result in futureData and printing its value.

It will print the below output :

--start--
Getting data..
--end--
Result : Hello after 5 seconds from a async function
  • main will call getData. Since, this is an asynchronous function, it will not wait for the execution.

  • Inside getData, it will wait for the result from getFutureString and wait for the result.

  • Finally, it will print the result that it got from getFutureString.

Note that, we can use await only inside an async function.

Similar tutorials :