Dart Async - 'Future' Class

| Page Views: 72

Dart Future Examples.

In dart's async library is a class called Future. This represents a computation whose return value might not yet be available. It normally will return the value of the computation when it completes at some time in the future. We use them mostly for potentially lengthy computations such as I/O and interaction with users.

Many methods in the Dart libraries return Futures when performing tasks. For example, when binding an HttpServer to a host and port, the bind() method returns a Future.

 HttpServer.bind('127.0.0.1', 4444).then((server) => print('${server.isBroadcast}')).catchError(print);

Future.then registers a callback function that runs when the Future's operation, in this case the bind() method, completes successfully. The value returned by the operation is passed into the callback function. In this example, the bind() method returns the HttpServer object. The callback function prints one of its properties. Future.catchError registers a callback function that runs if an error occurs within the Future.

Future Quick Examples and Snippets

1. Download Data and Return.

Let's say we want to download some data and return it in future after decoding it.

We can create an async method that will return a Future object:

  Future<String> getData() async {
    var response = await http.get(
      Uri.encodeFull("https://jsonplaceholder.typicode.com/posts"),
      headers: {
        "Accept": "application/json"
      }
    );
    data = JSON.decode(response.body);
    print(data[1]["title"]);

    return "Success!";
  }

How do You Feel after reading this?

According to scientists, we humans have 8 primary innate emotions: joy, acceptance, fear, surprise, sadness, disgust, anger, and anticipation. Feel free to tell us how you feel about this article using these emotes or via the comment section.

About Me.

After completing his Software Engineering bachelors program, Oclemy(Clement Ochieng) these days is a man of two lives. At day he works for a startup in Nairobi, Kenya. At night he works tirelessly on building ProgrammingWizards TV, a tv channel for student coders and this website to help share the source code. In between he practices Meditation and Self actualization to help him keep balance. He also likes going for long solo walks to connect more with nature.




Recommendations


What do You Think


Previous Post Next Post