Dart Concurrency: Futures

Dart Concurrency: Futures

ยท

2 min read

think of a Dart Future as a representation of a value that may not be available yet but will be at some point in the future. It's like a promise that something will happen.

For example, if you have a time-consuming task, like fetching data from the internet, you can use a Future to handle it. The Future says, "I'm working on getting the data, and once it's ready, I'll let you know."

Here's a Let's understand with one example:

Imagine you order food at a restaurant. The waiter gives you a token (the Future), and tells you, "Your food will be ready soon. Hold on to this token. When it's ready, we'll bring it to you." You can continue doing other things while waiting for your food. When the food is ready, the waiter fulfills the promise by bringing you the meal.

This snippet shows how we order food asynchronously. We initiate the order, proceed with other tasks, and handle the delivered result when the Future is fulfilled.

Future<String> fetchFood() {
  return Future.delayed(Duration(seconds: 5), () {
    return "Delicious meal"; // Simulating fetching data after 2 seconds
  });
}

void main() {
  print("Ordering food...");
  Future<String> foodFuture = fetchFood();

  print("Doing something else while waiting...");

  foodFuture.then((food) {
    print("Got the food: $food");
  });
}

Here ,we can see that when we run our program at that time we get print of first two statement and the last statement will run after 5 second, because we have used delayed in this.

  • This output will print after 5 second.

Did you find this article valuable?

Support Vinit Mepani (Flutter Developer) by becoming a sponsor. Any amount is appreciated!

ย