Future class in Dart Programming

Dart ProgrammingServer Side ProgrammingProgramming

There are different classes and keywords in Dart which we can use when we want to run Asynchronous code. The future class allows us to run asynchronous code and we can also avoid the callback hell with the help of it. A future mainly represents the result of an asynchronous operation.

In Dart, there are many standards library calls that return a future, some of them are −

  • http.get

  • SharedPreference.getInstance()

A future in Dart can have two states, these are −

  • Completed - When the operation of the future finishes and the future complete with a value or with an error.

  • Uncompleted - When a function is called, and it returned a future, the function queues up and returns an uncompleted future.

Syntax

Future<T>

In Dart, if a future doesn't produce any usable value then the future's type is Future<void>. Also, if the function doesn't explicitly return any value, then the return type is also Future<void>.

Example

Let's consider a small example where we are declaring a future that will display a message in a delayed fashion.

Consider the example shown below:
   Future<void> printDelayedMessage() {
      return Future.delayed(Duration(seconds: 4), () => print('Delayed Output.'));
}

void main() {
   printDelayedMessage();
   print('First output ...');
}

In the above example, we have a function named printDelayedMessage() that returns a future of type void, and we have a future that is using a method named delayed through which we are able to print the delayed output to the terminal.

Output

First output ...
Delayed Output.

It should be noted the second line of the output will be printed after 4 seconds.

Futures in Dart also allows us to register callbacks with the help of the then methods.

Example

Consider an example shown below −

void main() {
   var userEmailFuture = getUserEmail();
   // register callback
   userEmailFuture.then((userId) => print(userId));
   print('Hello');
}

// method which computes a future
Future<String> getUserEmail() {
   // simulate a long network call
   return Future.delayed(Duration(seconds: 4), () => "mukul@tutorialspoint.com");
}

Output

Hello
mukul@tutorialspoint.com
raja
Published on 21-May-2021 12:46:13
Advertisements