Dart Tutorial

Dart Chapter 10 of 15

Asynchronous Programming

Write code that waits without freezing: futures, async and await, streams, the event loop, isolates and generators.

Fetching data from the internet, reading a file and waiting for a tap all take time. Asynchronous code lets your program start such a task, carry on with other work, and come back when the result is ready. It is essential for any real app.

Lessons in this chapter

  1. Asynchronous Programming in Dart: An IntroductionUnderstand synchronous versus asynchronous code in Dart, why apps need async, and how Future, async, await and Stream fit together.
  2. Future in Dart: Working with Values That Arrive LaterLearn the Future class in Dart: states of a future, then, catchError, whenComplete, Future.value, Future.delayed and chaining futures.
  3. async and await in DartLearn how async and await work in Dart: write asynchronous code that reads like normal code, return futures, and avoid common mistakes.
  4. Error Handling in Asynchronous Dart CodeHandle errors in async Dart code with try and catch, catchError, timeouts and retries, and avoid unhandled future errors.
  5. Streams in Dart: Handling a Sequence of Async EventsLearn Stream in Dart: listen to events over time, use await for, create streams with async* and StreamController, and transform them.
  6. Single-Subscription vs Broadcast Streams in DartUnderstand the two kinds of stream in Dart: single-subscription and broadcast. Learn the differences, when to use each and how to convert.
  7. Running Futures in Parallel in Dart: Future.wait and MoreRun several async operations at once in Dart with Future.wait, record wait, Future.any and batching, and handle their errors.
  8. Completer in Dart: Creating Futures You Complete YourselfLearn how to use Completer in Dart to build a Future by hand, wrap callback-based APIs, and complete with a value or an error.
  9. The Dart Event Loop: Microtasks and Events ExplainedUnderstand how Dart runs asynchronous code on one thread: the event loop, event queue, microtask queue, and the order code executes.
  10. Isolates in Dart: Running Code in ParallelLearn isolates in Dart: run heavy work on another CPU core with Isolate.run, pass messages with ports, and keep your app responsive.
  11. Generators in Dart: sync*, async*, yield and yield*Learn generator functions in Dart: produce values lazily with sync* and async*, use yield and yield*, and build infinite sequences.
  12. Best Practices for Asynchronous Programming in DartA practical checklist for async Dart: await correctly, run work in parallel, handle errors, cancel subscriptions and avoid common pitfalls.