0Pricing
Flutter Mobile Development · Lesson

Futures & Async/Await

Understand Dart's `Future` class and the `async`/`await` keywords for performing non-blocking operations and handling delayed results.

What is Asynchronous Code?

In app development, we often need to perform tasks that take time, like fetching data from the internet or reading a file.

If these tasks block your app's main thread, your UI becomes unresponsive and freezes. This is a bad user experience!

Asynchronous programming allows your app to start a long-running task and continue doing other things (like updating the UI) while waiting for the task to finish.

The Problem with Blocking Code

Imagine a task that takes 3 seconds. If it runs on the main thread, your app will freeze for 3 seconds. Try running this example to see how it blocks:

void main() {
  print("Starting a long task...");
  // Simulate a long-running operation
  var result = _performHeavyCalculation();
  print("Task finished with result: $result");
  print("End of program.");
}

String _performHeavyCalculation() {
  // Simulate delay without async/await
  var startTime = DateTime.now();
  while (DateTime.now().difference(startTime).inSeconds < 3) {
    // Busy-wait, blocking the thread
  }
  return "Calculated Data";
}

All lessons in this course

  1. Futures & Async/Await
  2. HTTP Requests & JSON
  3. Error Handling in Async
  4. Streams & Reactive Data
← Back to Flutter Mobile Development