Dart Async - 'Future' Class

| Page Views: 14

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. This feedback helps us gauge our progress.

Help me Grow.

I set myself some growth ambitions I desire to achieve by this year's end regarding this website and my youtube channel. Am halfway. Help me reach them by:




Recommendations


What do You Think


Previous Post Next Post