{"id":503,"date":"2026-11-12T09:32:00","date_gmt":"2026-11-12T09:32:00","guid":{"rendered":"https:\/\/moiks.com\/blog\/?p=503"},"modified":"2026-11-12T07:39:08","modified_gmt":"2026-11-12T07:39:08","slug":"asynchronous-programming-dart-future-streams","status":"publish","type":"post","link":"https:\/\/moiks.com\/blog\/asynchronous-programming-dart-future-streams\/","title":{"rendered":"Asynchronous Programming in Dart: Future, async, await, Streams &#038; Error Handling (2026 Guide)"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">Modern mobile applications constantly perform operations that take time to complete.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A Flutter application may need to fetch information from an API, read data from a local database, download images, upload files, listen for real-time updates, or communicate with connected devices.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">If these operations block the user interface, the application becomes unresponsive.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Dart solves many of these problems through <strong>asynchronous programming<\/strong>, using <code>Future<\/code>, <code>async<\/code>, <code>await<\/code>, and <code>Stream<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Understanding these features is essential for building responsive, reliable Flutter applications.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In this tutorial, we&#8217;ll explore Dart&#8217;s asynchronous programming model, learn how to handle errors and concurrent operations, and build a practical Flutter Live Task Dashboard using <code>FutureBuilder<\/code> and <code>StreamBuilder<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This is <strong>Flutter Article 15<\/strong> in the Moiks Developer Blog Flutter Tutorials series.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">What You&#8217;ll Learn<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">By the end of this tutorial, you&#8217;ll understand:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Synchronous vs asynchronous programming.<\/li>\n\n\n\n<li>How Dart&#8217;s event loop works.<\/li>\n\n\n\n<li>What <code>Future&lt;T><\/code> represents.<\/li>\n\n\n\n<li>How to use <code>async<\/code> and <code>await<\/code>.<\/li>\n\n\n\n<li>How to handle errors with <code>try<\/code>, <code>catch<\/code>, and <code>finally<\/code>.<\/li>\n\n\n\n<li>How to execute concurrent asynchronous operations with <code>Future.wait<\/code>.<\/li>\n\n\n\n<li>How to use <code>Future.timeout<\/code>.<\/li>\n\n\n\n<li>What <code>Stream&lt;T><\/code> represents.<\/li>\n\n\n\n<li>Single-subscription vs broadcast streams.<\/li>\n\n\n\n<li>How to manage stream subscriptions.<\/li>\n\n\n\n<li>How to use <code>async*<\/code> and <code>yield<\/code>.<\/li>\n\n\n\n<li>How to use <code>FutureBuilder<\/code> and <code>StreamBuilder<\/code>.<\/li>\n\n\n\n<li>How to handle loading, empty, success, and error states.<\/li>\n\n\n\n<li>How to prevent outdated asynchronous results from updating the UI.<\/li>\n\n\n\n<li>How to test asynchronous Dart code and Flutter widgets.<\/li>\n<\/ul>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">1. What Is Asynchronous Programming in Dart?<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Asynchronous programming allows an application to initiate an operation and continue processing other work while waiting for that operation to complete.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Consider a Flutter application requesting data from a server.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The server may take several hundred milliseconds to respond.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Instead of freezing the interface, the application can display a loading indicator and remain responsive.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Synchronous Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>void main() {\n  print('Start');\n\n  print('Processing');\n\n  print('End');\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Start\nProcessing\nEnd<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Each statement executes in sequence.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Asynchronous Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>Future&lt;void&gt; main() async {\n  print('Start');\n\n  await Future&lt;void&gt;.delayed(\n    const Duration(seconds: 1),\n  );\n\n  print('End');\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The function suspends at <code>await<\/code> until the future completes.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Other eligible work can execute through the Dart event loop during this suspension.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Important:<\/strong> Asynchronous programming does not automatically move CPU-intensive work to another thread. Expensive synchronous computation can still block Flutter&#8217;s UI isolate.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">2. Understanding Dart&#8217;s Event Loop<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Dart uses an event-driven execution model.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Each isolate has its own memory and event loop.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">An isolate processes synchronous code and schedules asynchronous callbacks.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Two important scheduling mechanisms are:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>The microtask queue.<\/li>\n\n\n\n<li>The event queue.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Microtasks are generally processed before the next event.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>import 'dart:async';\n\nvoid main() {\n  print('A');\n\n  Future&lt;void&gt;.delayed(\n    Duration.zero,\n    () =&gt; print('D'),\n  );\n\n  scheduleMicrotask(\n    () =&gt; print('C'),\n  );\n\n  print('B');\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>A\nB\nC\nD<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The synchronous statements run first.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The microtask executes before the scheduled timer event.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Why Does This Matter?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Understanding the event loop helps explain:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Why asynchronous callbacks run later.<\/li>\n\n\n\n<li>Why long synchronous loops freeze the UI.<\/li>\n\n\n\n<li>How microtasks affect execution order.<\/li>\n\n\n\n<li>Why scheduling too many microtasks can delay event processing.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Avoid manually scheduling microtasks unless you have a specific reason.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For most Flutter applications, <code>async<\/code> and <code>await<\/code> provide a clearer abstraction.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">3. What Is a Future in Dart?<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">A <code>Future&lt;T&gt;<\/code> represents the eventual completion of an asynchronous operation.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A future can complete successfully with a value of type <code>T<\/code>, or complete with an error.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>Future&lt;String&gt; fetchUsername() async {\n  await Future&lt;void&gt;.delayed(\n    const Duration(seconds: 1),\n  );\n\n  return 'Alex';\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The return type:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Future&lt;String&gt;<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">indicates that the function eventually produces a string.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Consuming a Future<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>Future&lt;void&gt; main() async {\n  final username = await fetchUsername();\n\n  print(username);\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Alex<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Common Future Types<\/h3>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><tbody><tr><th>Type<\/th><th>Meaning<\/th><\/tr><tr><td><code>Future&lt;String&gt;<\/code><\/td><td>Eventually returns a string<\/td><\/tr><tr><td><code>Future&lt;int&gt;<\/code><\/td><td>Eventually returns an integer<\/td><\/tr><tr><td><code>Future&lt;bool&gt;<\/code><\/td><td>Eventually returns a boolean<\/td><\/tr><tr><td><code>Future&lt;List&lt;T&gt;&gt;<\/code><\/td><td>Eventually returns a list<\/td><\/tr><tr><td><code>Future&lt;void&gt;<\/code><\/td><td>Completes without a useful result<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">A future is not a background thread. It is a representation of asynchronous completion.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">4. Understanding the async Keyword<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The <code>async<\/code> keyword marks a function as asynchronous.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">An asynchronous function returns a <code>Future<\/code>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>Future&lt;int&gt; calculateTotal() async {\n  return 100 + 200;\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Usage:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Future&lt;void&gt; main() async {\n  final total = await calculateTotal();\n\n  print(total);\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>300<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Even though the calculation is simple, the asynchronous function returns a future.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">When Should You Use async?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Use <code>async<\/code> when a function needs to await asynchronous work or when it makes an asynchronous workflow clearer.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Do not mark every function as asynchronous unnecessarily.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For example, a normal price calculation should usually remain synchronous.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">5. Understanding the await Keyword<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The <code>await<\/code> keyword waits for a future&#8217;s completion without blocking the isolate in the way a synchronous waiting loop would.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>Future&lt;String&gt; loadProfile() async {\n  await Future&lt;void&gt;.delayed(\n    const Duration(milliseconds: 500),\n  );\n\n  return 'Profile loaded';\n}\n\nFuture&lt;void&gt; main() async {\n  print('Loading...');\n\n  final result = await loadProfile();\n\n  print(result);\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Loading...\nProfile loaded<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The code after <code>await<\/code> continues when the awaited operation completes successfully.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">If the future completes with an error, that error is propagated through the <code>await<\/code> expression.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">6. Future.then() vs async\/await<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Dart supports multiple ways to consume futures.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Using then()<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>Future&lt;String&gt; fetchData() async {\n  return 'Data loaded';\n}\n\nvoid main() {\n  fetchData().then((value) {\n    print(value);\n  });\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Using async\/await<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>Future&lt;void&gt; main() async {\n  final value = await fetchData();\n\n  print(value);\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Both approaches can work.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">However, <code>async<\/code> and <code>await<\/code> often make sequential asynchronous workflows easier to read.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Comparison<\/h3>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><tbody><tr><th>Feature<\/th><th>then()<\/th><th>async\/await<\/th><\/tr><tr><td>Style<\/td><td>Callback chaining<\/td><td>Sequential-looking code<\/td><\/tr><tr><td>Error handling<\/td><td><code>catchError()<\/code> or returned future<\/td><td><code>try\/catch<\/code><\/td><\/tr><tr><td>Multiple dependent operations<\/td><td>Can become nested<\/td><td>Usually easier to follow<\/td><\/tr><tr><td>Best use<\/td><td>Callback-style composition<\/td><td>Most application workflows<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">Neither approach is universally better. Choose the one that makes the operation clear.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">7. Sequential vs Concurrent Futures<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Suppose your application needs to load a user profile and application settings.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">If the operations are independent, they can often run concurrently.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Sequential Execution<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>Future&lt;String&gt; loadProfile() async {\n  await Future&lt;void&gt;.delayed(\n    const Duration(seconds: 1),\n  );\n\n  return 'Profile';\n}\n\nFuture&lt;String&gt; loadSettings() async {\n  await Future&lt;void&gt;.delayed(\n    const Duration(seconds: 1),\n  );\n\n  return 'Settings';\n}\n\nFuture&lt;void&gt; main() async {\n  final profile = await loadProfile();\n  final settings = await loadSettings();\n\n  print('$profile, $settings');\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The delays happen sequentially.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The example takes approximately two seconds, excluding overhead.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Concurrent Execution with Future.wait<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>Future&lt;void&gt; main() async {\n  final results = await Future.wait&lt;String&gt;(&#91;\n    loadProfile(),\n    loadSettings(),\n  ]);\n\n  print(results);\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Both operations are started before awaiting their combined completion.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The example takes approximately one second, excluding overhead.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Important Distinction<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><code>Future.wait<\/code> provides asynchronous concurrency, not necessarily parallel CPU execution.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For network requests and other independent I\/O operations, concurrency can reduce total waiting time.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For CPU-intensive tasks, isolates may be more appropriate.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">8. Error Handling with try, catch, and finally<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Asynchronous operations can fail.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Network requests may time out, files may be unavailable, and database operations may throw exceptions.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Dart supports structured exception handling.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>Future&lt;String&gt; fetchUser(bool shouldFail) async {\n  await Future&lt;void&gt;.delayed(\n    const Duration(milliseconds: 300),\n  );\n\n  if (shouldFail) {\n    throw Exception('Unable to load user');\n  }\n\n  return 'Alex';\n}\n\nFuture&lt;void&gt; main() async {\n  try {\n    final user = await fetchUser(true);\n\n    print(user);\n  } catch (error) {\n    print('Error: $error');\n  } finally {\n    print('Operation finished');\n  }\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The <code>catch<\/code> block handles errors thrown by the awaited operation.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The <code>finally<\/code> block executes when control leaves the <code>try\/catch<\/code> structure, whether the operation succeeds or fails.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Catching Specific Exceptions<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>try {\n  await fetchUser(true);\n} on FormatException catch (error) {\n  print('Invalid format: $error');\n} on Exception catch (error) {\n  print('Operation failed: $error');\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Specific exception handling makes recovery behavior clearer.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Avoid silently ignoring errors.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">9. Future.timeout()<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Sometimes an operation takes longer than the application should wait.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Dart provides <code>Future.timeout()<\/code>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>Future&lt;String&gt; slowRequest() async {\n  await Future&lt;void&gt;.delayed(\n    const Duration(seconds: 5),\n  );\n\n  return 'Completed';\n}\n\nFuture&lt;void&gt; main() async {\n  try {\n    final result = await slowRequest().timeout(\n      const Duration(seconds: 2),\n    );\n\n    print(result);\n  } on TimeoutException {\n    print('Request timed out');\n  }\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Add the import:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import 'dart:async';<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Request timed out<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Important Timeout Behavior<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Calling <code>timeout()<\/code> does not necessarily cancel the original operation.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The underlying request may continue executing.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For real networking or other resources, use the cancellation capabilities supported by the relevant API or package.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">10. What Is a Stream in Dart?<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">A <code>Future<\/code> represents one eventual completion.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A <code>Stream<\/code> represents a sequence of asynchronous events.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For example, a stream may deliver:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Location updates.<\/li>\n\n\n\n<li>Download progress.<\/li>\n\n\n\n<li>Bluetooth sensor readings.<\/li>\n\n\n\n<li>Database changes.<\/li>\n\n\n\n<li>Chat messages.<\/li>\n\n\n\n<li>Timer ticks.<\/li>\n\n\n\n<li>Live application activity.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Basic Stream Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>Stream&lt;int&gt; countNumbers() async* {\n  for (var number = 1; number &lt;= 5; number++) {\n    await Future&lt;void&gt;.delayed(\n      const Duration(milliseconds: 300),\n    );\n\n    yield number;\n  }\n}\n\nFuture&lt;void&gt; main() async {\n  await for (final number in countNumbers()) {\n    print(number);\n  }\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>1\n2\n3\n4\n5<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The stream emits values over time.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">11. Understanding async* and yield<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Dart uses <code>async*<\/code> to create asynchronous generator functions.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The <code>yield<\/code> keyword emits a value to the stream.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>Stream&lt;String&gt; loadMessages() async* {\n  yield 'Connecting...';\n\n  await Future&lt;void&gt;.delayed(\n    const Duration(milliseconds: 500),\n  );\n\n  yield 'Connected';\n\n  await Future&lt;void&gt;.delayed(\n    const Duration(milliseconds: 500),\n  );\n\n  yield 'Data received';\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Consume it:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Future&lt;void&gt; main() async {\n  await for (final message in loadMessages()) {\n    print(message);\n  }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">yield vs yield*<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><code>yield<\/code> emits one event.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code>yield*<\/code> forwards events from another stream.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Stream&lt;int&gt; firstStream() async* {\n  yield 1;\n  yield 2;\n}\n\nStream&lt;int&gt; combinedStream() async* {\n  yield* firstStream();\n  yield 3;\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The combined stream emits <code>1<\/code>, <code>2<\/code>, and <code>3<\/code>.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">12. Single-Subscription vs Broadcast Streams<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Dart supports two important stream categories.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Single-Subscription Streams<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">A single-subscription stream is intended for one listener.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">An <code>async*<\/code> generator normally produces a single-subscription stream.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>final stream = countNumbers();\n\nstream.listen(print);<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Trying to listen to the same single-subscription stream again generally throws a state error.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Broadcast Streams<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">A broadcast stream can support multiple listeners.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import 'dart:async';\n\nvoid main() async {\n  final controller =\n      StreamController&lt;int&gt;.broadcast();\n\n  final first = controller.stream.listen(\n    (value) =&gt; print('First: $value'),\n  );\n\n  final second = controller.stream.listen(\n    (value) =&gt; print('Second: $value'),\n  );\n\n  controller.add(10);\n  controller.add(20);\n\n  await Future&lt;void&gt;.delayed(Duration.zero);\n\n  await first.cancel();\n  await second.cancel();\n  await controller.close();\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Which Should You Choose?<\/h3>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><tbody><tr><th>Requirement<\/th><th>Stream Type<\/th><\/tr><tr><td>One consumer of an event sequence<\/td><td>Single-subscription<\/td><\/tr><tr><td>Multiple independent listeners<\/td><td>Broadcast<\/td><\/tr><tr><td>File reading<\/td><td>Usually single-subscription<\/td><\/tr><tr><td>Shared application events<\/td><td>Broadcast may be appropriate<\/td><\/tr><tr><td><code>async*<\/code> generator<\/td><td>Normally single-subscription<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">Broadcast streams do not automatically replay previously emitted events to new listeners.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">13. StreamSubscription and Cancellation<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">When using <code>listen()<\/code>, Dart returns a <code>StreamSubscription<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">You can pause, resume, or cancel the subscription.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>import 'dart:async';\n\nFuture&lt;void&gt; main() async {\n  final controller = StreamController&lt;int&gt;();\n\n  final subscription = controller.stream.listen(\n    (value) {\n      print('Received: $value');\n    },\n  );\n\n  controller.add(10);\n  controller.add(20);\n\n  await Future&lt;void&gt;.delayed(Duration.zero);\n\n  await subscription.cancel();\n\n  await controller.close();\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Why Is Cancellation Important in Flutter?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">A widget may be removed while a stream is still active.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">If the subscription is not managed correctly, it can continue holding resources or executing callbacks.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A common pattern is:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>@override\nvoid dispose() {\n  subscription.cancel();\n  super.dispose();\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">For subscriptions that require asynchronous cancellation, initiate cancellation in <code>dispose()<\/code> and ensure any resource ownership is handled appropriately.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Widgets using <code>StreamBuilder<\/code> manage their own subscriptions when configured correctly.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">14. FutureBuilder in Flutter<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\"><code>FutureBuilder&lt;T&gt;<\/code> builds a widget based on a future&#8217;s state.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It is commonly used for loading data from asynchronous sources.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>Future&lt;String&gt; loadMessage() async {\n  await Future&lt;void&gt;.delayed(\n    const Duration(seconds: 1),\n  );\n\n  return 'Welcome to Flutter';\n}\n\nclass MessageScreen extends StatefulWidget {\n  const MessageScreen({super.key});\n\n  @override\n  State&lt;MessageScreen&gt; createState() =&gt;\n      _MessageScreenState();\n}\n\nclass _MessageScreenState extends State&lt;MessageScreen&gt; {\n  late final Future&lt;String&gt; messageFuture;\n\n  @override\n  void initState() {\n    super.initState();\n    messageFuture = loadMessage();\n  }\n\n  @override\n  Widget build(BuildContext context) {\n    return FutureBuilder&lt;String&gt;(\n      future: messageFuture,\n      builder: (context, snapshot) {\n        if (snapshot.connectionState !=\n            ConnectionState.done) {\n          return const CircularProgressIndicator();\n        }\n\n        if (snapshot.hasError) {\n          return Text('Error: ${snapshot.error}');\n        }\n\n        return Text(snapshot.data ?? 'No message');\n      },\n    );\n  }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Why Create the Future in initState()?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Avoid creating a new future every time <code>build()<\/code> executes.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Recreating the future in <code>build()<\/code> can cause unnecessary repeated requests.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Create it in <code>initState()<\/code> or another suitable lifecycle method, then update it intentionally when refreshing.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">15. StreamBuilder in Flutter<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\"><code>StreamBuilder&lt;T&gt;<\/code> rebuilds its widget when new stream events are observed.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>Stream&lt;int&gt; timerStream() async* {\n  for (var i = 1; i &lt;= 10; i++) {\n    await Future&lt;void&gt;.delayed(\n      const Duration(seconds: 1),\n    );\n\n    yield i;\n  }\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Inside a stateful widget, initialize the stream once:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>late final Stream&lt;int&gt; counterStream;\n\n@override\nvoid initState() {\n  super.initState();\n  counterStream = timerStream();\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Then build the UI:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>StreamBuilder&lt;int&gt;(\n  stream: counterStream,\n  initialData: 0,\n  builder: (context, snapshot) {\n    if (snapshot.hasError) {\n      return const Text('Stream error');\n    }\n\n    return Text(\n      'Count: ${snapshot.data ?? 0}',\n    );\n  },\n)<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><code>StreamBuilder<\/code> subscribes to the stream and rebuilds when relevant events arrive.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It does not guarantee that every intermediate event will result in a separately rendered frame.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h1 class=\"wp-block-heading\">16. Practical Flutter Project: Live Task Dashboard<\/h1>\n\n\n\n<p class=\"wp-block-paragraph\">Now let&#8217;s build a complete Flutter application using asynchronous programming.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The app demonstrates two different asynchronous workflows.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Future-based data loading:<\/strong> Simulated API calls retrieve a list of tasks and dashboard statistics.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Stream-based live updates:<\/strong> A stream emits activity messages periodically.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The application also supports loading indicators, retry, simulated failures, task completion, and proper resource management.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Project Features<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Material 3 interface.<\/li>\n\n\n\n<li>Concurrent asynchronous data loading.<\/li>\n\n\n\n<li>Generic result handling through typed models.<\/li>\n\n\n\n<li><code>FutureBuilder<\/code> for dashboard data.<\/li>\n\n\n\n<li><code>StreamBuilder<\/code> for live activity.<\/li>\n\n\n\n<li>Searchable task list.<\/li>\n\n\n\n<li>Task completion controls.<\/li>\n\n\n\n<li>Retry functionality.<\/li>\n\n\n\n<li>Simulated API errors.<\/li>\n\n\n\n<li>Automatic stream cleanup.<\/li>\n\n\n\n<li>Unit and widget tests.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">The example does not require an internet connection or third-party dependencies.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Step 1: Create the Project<\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>flutter create dart_async_demo\ncd dart_async_demo<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Project Structure<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>lib\/\n\u251c\u2500\u2500 main.dart\n\u251c\u2500\u2500 models\/\n\u2502   \u251c\u2500\u2500 task.dart\n\u2502   \u2514\u2500\u2500 dashboard_data.dart\n\u251c\u2500\u2500 services\/\n\u2502   \u2514\u2500\u2500 dashboard_service.dart\n\u2514\u2500\u2500 widgets\/\n    \u2514\u2500\u2500 task_card.dart\n\ntest\/\n\u251c\u2500\u2500 dashboard_service_test.dart\n\u2514\u2500\u2500 dashboard_widget_test.dart<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Step 2: Create the Task Model<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Create <code>lib\/models\/task.dart<\/code>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>class Task {\n  final int id;\n  final String title;\n  final bool completed;\n\n  const Task({\n    required this.id,\n    required this.title,\n    this.completed = false,\n  });\n\n  Task copyWith({bool? completed}) {\n    return Task(\n      id: id,\n      title: title,\n      completed: completed ?? this.completed,\n    );\n  }\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The model is immutable.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Its <code>copyWith()<\/code> method produces an updated object.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Step 3: Create the Dashboard Data Model<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Create <code>lib\/models\/dashboard_data.dart<\/code>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import 'task.dart';\n\nclass DashboardData {\n  final List&lt;Task&gt; tasks;\n  final String userName;\n\n  DashboardData({\n    required List&lt;Task&gt; tasks,\n    required this.userName,\n  }) : tasks = List.unmodifiable(tasks);\n\n  int get total =&gt; tasks.length;\n\n  int get completed =&gt;\n      tasks.where((task) =&gt; task.completed).length;\n\n  int get pending =&gt; total - completed;\n\n  DashboardData toggleTask(int id) {\n    return DashboardData(\n      userName: userName,\n      tasks: &#91;\n        for (final task in tasks)\n          if (task.id == id)\n            task.copyWith(\n              completed: !task.completed,\n            )\n          else\n            task,\n      ],\n    );\n  }\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The dashboard data object provides task statistics and immutable updates.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Step 4: Create the Asynchronous Service<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Create <code>lib\/services\/dashboard_service.dart<\/code>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import 'dart:async';\n\nimport '..\/models\/dashboard_data.dart';\nimport '..\/models\/task.dart';\n\nclass DashboardService {\n  final Duration requestDelay;\n  final Duration activityInterval;\n\n  bool _disposed = false;\n\n  DashboardService({\n    this.requestDelay =\n        const Duration(milliseconds: 600),\n    this.activityInterval =\n        const Duration(seconds: 2),\n  });\n\n  Future&lt;List&lt;Task&gt;&gt; fetchTasks({\n    bool simulateError = false,\n  }) async {\n    await Future&lt;void&gt;.delayed(requestDelay);\n\n    if (_disposed) {\n      throw StateError('Service disposed');\n    }\n\n    if (simulateError) {\n      throw Exception('Unable to load tasks');\n    }\n\n    return const &#91;\n      Task(\n        id: 1,\n        title: 'Learn Dart Futures',\n      ),\n      Task(\n        id: 2,\n        title: 'Practice async and await',\n      ),\n      Task(\n        id: 3,\n        title: 'Explore Dart Streams',\n      ),\n      Task(\n        id: 4,\n        title: 'Build Flutter dashboard',\n        completed: true,\n      ),\n    ];\n  }\n\n  Future&lt;String&gt; fetchUserName() async {\n    await Future&lt;void&gt;.delayed(requestDelay);\n\n    if (_disposed) {\n      throw StateError('Service disposed');\n    }\n\n    return 'Flutter Developer';\n  }\n\n  Future&lt;DashboardData&gt; loadDashboard({\n    bool simulateError = false,\n  }) async {\n    final results = await Future.wait&lt;Object&gt;(&#91;\n      fetchTasks(simulateError: simulateError),\n      fetchUserName(),\n    ]);\n\n    return DashboardData(\n      tasks: results&#91;0] as List&lt;Task&gt;,\n      userName: results&#91;1] as String,\n    );\n  }\n\n  Stream&lt;String&gt; activityStream() async* {\n    var counter = 0;\n\n    while (!_disposed) {\n      await Future&lt;void&gt;.delayed(\n        activityInterval,\n      );\n\n      if (_disposed) break;\n\n      counter++;\n\n      yield 'Activity update #$counter';\n    }\n  }\n\n  void dispose() {\n    _disposed = true;\n  }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Understanding the Service<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The service demonstrates several concepts.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Future-based operations:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Future&lt;List&lt;Task&gt;&gt; fetchTasks()<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Concurrent loading:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Future.wait&lt;Object&gt;(...)<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Asynchronous generator:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Stream&lt;String&gt; activityStream() async*<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Periodic event emission:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>yield 'Activity update #$counter';<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Resource cleanup:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>void dispose() {\n  _disposed = true;\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The service uses a boolean flag to stop future stream events after disposal. This is sufficient for the educational simulation, but it does not interrupt an in-progress <code>Future.delayed<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For real HTTP requests, use an API client with explicit cancellation or appropriate lifecycle handling.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Step 5: Create the Task Card Widget<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Create <code>lib\/widgets\/task_card.dart<\/code>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import 'package:flutter\/material.dart';\n\nimport '..\/models\/task.dart';\n\nclass TaskCard extends StatelessWidget {\n  final Task task;\n  final ValueChanged&lt;bool?&gt; onChanged;\n\n  const TaskCard({\n    super.key,\n    required this.task,\n    required this.onChanged,\n  });\n\n  @override\n  Widget build(BuildContext context) {\n    return Card(\n      child: CheckboxListTile(\n        value: task.completed,\n        onChanged: onChanged,\n        title: Text(\n          task.title,\n          style: TextStyle(\n            decoration: task.completed\n                ? TextDecoration.lineThrough\n                : null,\n          ),\n        ),\n        secondary: Icon(\n          task.completed\n              ? Icons.check_circle\n              : Icons.pending_actions,\n        ),\n      ),\n    );\n  }\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">This widget displays a task and allows its completion state to be changed.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Step 6: Build the Flutter Dashboard UI<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Replace <code>lib\/main.dart<\/code>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import 'package:flutter\/material.dart';\n\nimport 'models\/dashboard_data.dart';\nimport 'services\/dashboard_service.dart';\nimport 'widgets\/task_card.dart';\n\nvoid main() {\n  runApp(const AsyncDashboardApp());\n}\n\nclass AsyncDashboardApp extends StatelessWidget {\n  const AsyncDashboardApp({super.key});\n\n  @override\n  Widget build(BuildContext context) {\n    return MaterialApp(\n      title: 'Dart Async Dashboard',\n      debugShowCheckedModeBanner: false,\n      theme: ThemeData(\n        colorScheme: ColorScheme.fromSeed(\n          seedColor: const Color(0xFF004B64),\n        ),\n        useMaterial3: true,\n      ),\n      home: const AsyncDashboardScreen(),\n    );\n  }\n}\n\nclass AsyncDashboardScreen extends StatefulWidget {\n  const AsyncDashboardScreen({super.key});\n\n  @override\n  State&lt;AsyncDashboardScreen&gt; createState() =&gt;\n      _AsyncDashboardScreenState();\n}\n\nclass _AsyncDashboardScreenState\n    extends State&lt;AsyncDashboardScreen&gt; {\n  late final DashboardService service;\n\n  late Future&lt;DashboardData&gt; dashboardFuture;\n  late Stream&lt;String&gt; activityUpdates;\n\n  DashboardData? currentData;\n\n  bool simulateError = false;\n  String searchQuery = '';\n  int requestVersion = 0;\n\n  @override\n  void initState() {\n    super.initState();\n\n    service = DashboardService();\n    activityUpdates = service.activityStream();\n\n    loadDashboard();\n  }\n\n  void loadDashboard() {\n    final version = ++requestVersion;\n\n    currentData = null;\n\n    dashboardFuture = service.loadDashboard(\n      simulateError: simulateError,\n    ).then((data) {\n      if (mounted &amp;&amp; version == requestVersion) {\n        currentData = data;\n      }\n\n      return data;\n    });\n  }\n\n  void refreshDashboard() {\n    setState(() {\n      loadDashboard();\n    });\n  }\n\n  void toggleTask(int id) {\n    final data = currentData;\n\n    if (data == null) return;\n\n    setState(() {\n      currentData = data.toggleTask(id);\n    });\n  }\n\n  @override\n  void dispose() {\n    requestVersion++;\n    service.dispose();\n    super.dispose();\n  }\n\n  Widget buildSummary(DashboardData data) {\n    return Card(\n      child: Padding(\n        padding: const EdgeInsets.all(16),\n        child: Wrap(\n          alignment: WrapAlignment.spaceAround,\n          spacing: 24,\n          runSpacing: 12,\n          children: &#91;\n            summaryItem(\n              'Total',\n              data.total,\n              Icons.list_alt,\n            ),\n            summaryItem(\n              'Pending',\n              data.pending,\n              Icons.pending_actions,\n            ),\n            summaryItem(\n              'Completed',\n              data.completed,\n              Icons.check_circle_outline,\n            ),\n          ],\n        ),\n      ),\n    );\n  }\n\n  Widget summaryItem(\n    String label,\n    int count,\n    IconData icon,\n  ) {\n    return Column(\n      mainAxisSize: MainAxisSize.min,\n      children: &#91;\n        Icon(icon),\n        const SizedBox(height: 4),\n        Text(\n          '$count',\n          style: const TextStyle(\n            fontSize: 22,\n            fontWeight: FontWeight.bold,\n          ),\n        ),\n        Text(label),\n      ],\n    );\n  }\n\n  Widget buildTaskList(DashboardData data) {\n    final visibleTasks = data.tasks.where((task) {\n      return task.title.toLowerCase().contains(\n        searchQuery.toLowerCase(),\n      );\n    }).toList();\n\n    if (visibleTasks.isEmpty) {\n      return const Center(\n        child: Text('No tasks found'),\n      );\n    }\n\n    return ListView.builder(\n      shrinkWrap: true,\n      physics: const NeverScrollableScrollPhysics(),\n      itemCount: visibleTasks.length,\n      itemBuilder: (context, index) {\n        final task = visibleTasks&#91;index];\n\n        return TaskCard(\n          task: task,\n          onChanged: (_) =&gt; toggleTask(task.id),\n        );\n      },\n    );\n  }\n\n  Widget buildDashboard(\n    AsyncSnapshot&lt;DashboardData&gt; snapshot,\n  ) {\n    if (snapshot.connectionState !=\n        ConnectionState.done) {\n      return const Center(\n        child: Padding(\n          padding: EdgeInsets.all(40),\n          child: CircularProgressIndicator(),\n        ),\n      );\n    }\n\n    if (snapshot.hasError) {\n      return Center(\n        child: Column(\n          mainAxisSize: MainAxisSize.min,\n          children: &#91;\n            const Icon(\n              Icons.error_outline,\n              size: 48,\n              color: Colors.red,\n            ),\n            const SizedBox(height: 12),\n            const Text('Unable to load dashboard'),\n            const SizedBox(height: 12),\n            FilledButton.icon(\n              onPressed: refreshDashboard,\n              icon: const Icon(Icons.refresh),\n              label: const Text('Retry'),\n            ),\n          ],\n        ),\n      );\n    }\n\n    final data = currentData ?? snapshot.data;\n\n    if (data == null) {\n      return const Center(\n        child: Text('No dashboard data'),\n      );\n    }\n\n    return Column(\n      crossAxisAlignment: CrossAxisAlignment.stretch,\n      children: &#91;\n        Text(\n          'Welcome, ${data.userName}',\n          style: Theme.of(context)\n              .textTheme\n              .titleLarge,\n        ),\n\n        const SizedBox(height: 12),\n\n        buildSummary(data),\n\n        const SizedBox(height: 16),\n\n        TextField(\n          onChanged: (value) {\n            setState(() {\n              searchQuery = value;\n            });\n          },\n          decoration: const InputDecoration(\n            labelText: 'Search Tasks',\n            prefixIcon: Icon(Icons.search),\n            border: OutlineInputBorder(),\n          ),\n        ),\n\n        const SizedBox(height: 12),\n\n        buildTaskList(data),\n      ],\n    );\n  }\n\n  Widget buildActivity() {\n    return Card(\n      child: Padding(\n        padding: const EdgeInsets.all(16),\n        child: Column(\n          crossAxisAlignment:\n              CrossAxisAlignment.start,\n          children: &#91;\n            const Text(\n              'Live Activity',\n              style: TextStyle(\n                fontSize: 18,\n                fontWeight: FontWeight.bold,\n              ),\n            ),\n\n            const SizedBox(height: 8),\n\n            StreamBuilder&lt;String&gt;(\n              stream: activityUpdates,\n              builder: (context, snapshot) {\n                if (snapshot.hasError) {\n                  return const Text(\n                    'Activity stream error',\n                  );\n                }\n\n                return Text(\n                  snapshot.data ??\n                      'Waiting for activity...',\n                );\n              },\n            ),\n          ],\n        ),\n      ),\n    );\n  }\n\n  @override\n  Widget build(BuildContext context) {\n    return Scaffold(\n      appBar: AppBar(\n        title: const Text('Live Task Dashboard'),\n        centerTitle: true,\n        actions: &#91;\n          IconButton(\n            tooltip: 'Refresh dashboard',\n            onPressed: refreshDashboard,\n            icon: const Icon(Icons.refresh),\n          ),\n        ],\n      ),\n      body: SafeArea(\n        child: Center(\n          child: ConstrainedBox(\n            constraints: const BoxConstraints(\n              maxWidth: 760,\n            ),\n            child: ListView(\n              padding: const EdgeInsets.all(16),\n              children: &#91;\n                SwitchListTile(\n                  title: const Text(\n                    'Simulate API Error',\n                  ),\n                  subtitle: const Text(\n                    'Enable and refresh to test retry',\n                  ),\n                  value: simulateError,\n                  onChanged: (value) {\n                    setState(() {\n                      simulateError = value;\n                    });\n                  },\n                ),\n\n                const SizedBox(height: 12),\n\n                FutureBuilder&lt;DashboardData&gt;(\n                  future: dashboardFuture,\n                  builder: (context, snapshot) {\n                    return buildDashboard(snapshot);\n                  },\n                ),\n\n                const SizedBox(height: 16),\n\n                buildActivity(),\n              ],\n            ),\n          ),\n        ),\n      ),\n    );\n  }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">How the UI Works<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The application uses <code>FutureBuilder<\/code> to display the dashboard&#8217;s loading, success, and error states.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It uses <code>StreamBuilder<\/code> to display periodically emitted activity messages.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The refresh button starts a new dashboard load.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The <code>requestVersion<\/code> value helps prevent an older request from replacing the latest dashboard state.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The task completion feature updates the in-memory dashboard data without requiring another simulated API request.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Important Production Consideration<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The sample uses <code>Future.wait&lt;Object&gt;<\/code> with explicit casts to combine results of different types.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For larger applications, a typed record can provide a cleaner alternative:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Future&lt;(List&lt;Task&gt;, String)&gt; loadParts() async {\n  final tasksFuture = fetchTasks();\n  final userFuture = fetchUserName();\n\n  final tasks = await tasksFuture;\n  final user = await userFuture;\n\n  return (tasks, user);\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Both futures are started before either result is awaited.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The example project uses <code>Future.wait<\/code> to demonstrate that API directly.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Step 7: Run the Application<\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>flutter run<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Expected Behavior<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">When the application opens:<\/p>\n\n\n\n<ol start=\"1\" class=\"wp-block-list\">\n<li>A loading indicator appears.<\/li>\n\n\n\n<li>The simulated dashboard requests complete.<\/li>\n\n\n\n<li>Four tasks appear.<\/li>\n\n\n\n<li>The summary displays total, pending, and completed tasks.<\/li>\n\n\n\n<li>Live activity messages update periodically.<\/li>\n\n\n\n<li>Users can search and complete tasks.<\/li>\n\n\n\n<li>Refresh reloads the dashboard.<\/li>\n\n\n\n<li>Enabling simulated API errors and refreshing displays an error state.<\/li>\n<\/ol>\n\n\n\n<p class=\"wp-block-paragraph\">The dashboard starts with four tasks, one completed and three pending.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The activity stream continues emitting events while the screen remains active.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h1 class=\"wp-block-heading\">17. Unit Testing Asynchronous Dart Code<\/h1>\n\n\n\n<p class=\"wp-block-paragraph\">Create <code>test\/dashboard_service_test.dart<\/code>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import 'package:flutter_test\/flutter_test.dart';\n\nimport 'package:dart_async_demo\/services\/dashboard_service.dart';\n\nvoid main() {\n  late DashboardService service;\n\n  setUp(() {\n    service = DashboardService(\n      requestDelay: Duration.zero,\n      activityInterval:\n          const Duration(milliseconds: 10),\n    );\n  });\n\n  tearDown(() {\n    service.dispose();\n  });\n\n  test('Loads tasks asynchronously', () async {\n    final tasks = await service.fetchTasks();\n\n    expect(tasks.length, 4);\n    expect(tasks.first.title, 'Learn Dart Futures');\n  });\n\n  test('Loads dashboard data', () async {\n    final dashboard = await service.loadDashboard();\n\n    expect(dashboard.userName, 'Flutter Developer');\n    expect(dashboard.total, 4);\n    expect(dashboard.completed, 1);\n    expect(dashboard.pending, 3);\n  });\n\n  test('Handles simulated errors', () async {\n    expect(\n      service.loadDashboard(simulateError: true),\n      throwsException,\n    );\n  });\n\n  test('Emits stream activity', () async {\n    final firstEvent =\n        await service.activityStream().first;\n\n    expect(firstEvent, 'Activity update #1');\n  });\n\n  test('Toggles task completion', () async {\n    final dashboard = await service.loadDashboard();\n\n    final updated = dashboard.toggleTask(1);\n\n    expect(updated.completed, 2);\n    expect(updated.pending, 2);\n    expect(dashboard.completed, 1);\n  });\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">What These Tests Cover<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The tests verify asynchronous task loading, concurrent dashboard loading, simulated exceptions, stream events, and immutable task updates.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Run:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>flutter test test\/dashboard_service_test.dart<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The stream test consumes only the first event, so it does not wait for the infinite stream to finish.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">18. Flutter Widget Testing<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Create <code>test\/dashboard_widget_test.dart<\/code>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import 'package:flutter\/material.dart';\nimport 'package:flutter_test\/flutter_test.dart';\n\nimport 'package:dart_async_demo\/main.dart';\n\nvoid main() {\n  testWidgets(\n    'Displays dashboard title',\n    (tester) async {\n      await tester.pumpWidget(\n        const AsyncDashboardApp(),\n      );\n\n      expect(\n        find.text('Live Task Dashboard'),\n        findsOneWidget,\n      );\n    },\n  );\n\n  testWidgets(\n    'Displays loading indicator',\n    (tester) async {\n      await tester.pumpWidget(\n        const AsyncDashboardApp(),\n      );\n\n      expect(\n        find.byType(CircularProgressIndicator),\n        findsOneWidget,\n      );\n    },\n  );\n\n  testWidgets(\n    'Loads dashboard tasks',\n    (tester) async {\n      await tester.pumpWidget(\n        const AsyncDashboardApp(),\n      );\n\n      await tester.pump(\n        const Duration(milliseconds: 700),\n      );\n\n      await tester.pump();\n\n      expect(\n        find.text('Learn Dart Futures'),\n        findsOneWidget,\n      );\n    },\n  );\n\n  testWidgets(\n    'Displays live activity section',\n    (tester) async {\n      await tester.pumpWidget(\n        const AsyncDashboardApp(),\n      );\n\n      expect(\n        find.text('Live Activity'),\n        findsOneWidget,\n      );\n    },\n  );\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Running Widget Tests<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>flutter test test\/dashboard_widget_test.dart<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Run the complete test suite:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>flutter test<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Run static analysis:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>flutter analyze<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Testing Note<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Avoid using <code>pumpAndSettle()<\/code> indiscriminately when widgets contain continuously running animations or streams.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In this example, controlled <code>pump()<\/code> calls are preferable because the activity stream emits events indefinitely while active.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For larger applications, inject fake services or configurable delays so tests do not depend on real waiting times.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">19. Common Mistakes in Dart Asynchronous Programming<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 1: Forgetting await<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>final result = fetchUsername();<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Here, <code>result<\/code> is a future, not the username.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">If you need the completed value, use:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>final result = await fetchUsername();<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 2: Blocking the UI Isolate<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Avoid expensive synchronous computations inside widget callbacks or build methods.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Use isolates for substantial CPU-intensive work when appropriate.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 3: Creating Futures Inside build()<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Avoid:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>FutureBuilder(\n  future: fetchData(),\n  builder: ...,\n)<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">when <code>fetchData()<\/code> starts a new operation every time it is called.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Prefer creating and retaining the future in an appropriate lifecycle method.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 4: Ignoring Errors<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Always consider what happens when an asynchronous operation fails.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Display meaningful messages and provide recovery actions when appropriate.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 5: Forgetting Stream Cancellation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Subscriptions that outlive their owners may waste resources or cause unexpected callbacks.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Cancel manually managed subscriptions when they are no longer needed.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 6: Assuming Future.timeout Cancels Work<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">A timeout changes which result the caller receives, but does not automatically terminate the underlying operation.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 7: Calling setState After dispose()<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">An asynchronous operation may complete after a widget is removed.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Check <code>mounted<\/code> before updating state from an asynchronous callback.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 8: Ignoring Request Races<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">An older request may complete after a newer request.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Use request identifiers, cancellation mechanisms, or state management patterns to prevent stale results from replacing current data.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 9: Misusing Future.wait<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Use <code>Future.wait<\/code> for independent operations that can execute concurrently.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Do not run dependent operations concurrently when one requires another&#8217;s result.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 10: Treating Async as Parallelism<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><code>async<\/code> and <code>await<\/code> do not automatically execute expensive computations on separate CPU cores.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Dart isolates provide a different mechanism for concurrent execution of CPU-bound work.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">20. Best Practices for Flutter Async Programming<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">Prefer async\/await for Readability<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Use <code>async<\/code> and <code>await<\/code> for clear asynchronous control flow.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Keep Futures Outside build()<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Initialize futures in <code>initState()<\/code>, update them intentionally, or manage them through an appropriate application state layer.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Handle Every Important State<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Consider loading, success, empty, error, retry, and cancellation behavior.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Use Timeouts Where Appropriate<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Avoid leaving users waiting indefinitely for operations that may never complete.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Cancel Owned Resources<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Dispose of subscriptions, controllers, and other resources when their owners are destroyed.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Avoid Unnecessary Concurrent Requests<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Concurrency can improve responsiveness, but excessive simultaneous requests may overload services or consume resources.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Separate Business Logic from Widgets<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Keep API access, data transformation, and domain logic in services or repositories.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Test Success and Failure Paths<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">A reliable asynchronous application needs tests for both normal operation and errors.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Avoid Stale UI Updates<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Prevent outdated requests from overwriting newer application state.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Understand the Difference Between Futures and Streams<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Use a future for a single eventual result.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Use a stream for a sequence of asynchronous events.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">21. Frequently Asked Questions<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">What is asynchronous programming in Dart?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Asynchronous programming allows Dart applications to perform operations that take time without blocking other eligible work on the event loop.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">What is Future in Dart?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">A <code>Future&lt;T&gt;<\/code> represents an operation that will eventually complete with a value of type <code>T<\/code> or an error.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">What is async in Dart?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The <code>async<\/code> keyword marks a function as asynchronous and makes it return a future.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">What is await in Dart?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The <code>await<\/code> keyword suspends an asynchronous function until a future completes.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">What is the difference between Future and Stream?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">A future represents one eventual completion, while a stream delivers a sequence of asynchronous events.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">What is Future.wait?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><code>Future.wait<\/code> combines multiple futures and completes when all succeed, or completes with an error according to its error-handling configuration.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Does Future.wait execute operations in parallel?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">It allows asynchronous operations to progress concurrently, but it does not automatically create separate threads or isolates.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">What is Future.timeout?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><code>Future.timeout<\/code> provides a timeout for waiting on a future&#8217;s result. It does not necessarily cancel the original operation.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">What is async* in Dart?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><code>async*<\/code> declares an asynchronous generator that produces a stream.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">What does yield mean in Dart?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><code>yield<\/code> emits an event from a synchronous or asynchronous generator.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">What is yield*?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><code>yield*<\/code> delegates event emission to another iterable or stream, depending on the generator type.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">What is StreamSubscription?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><code>StreamSubscription<\/code> represents a listener attached to a stream and provides methods for cancellation, pausing, and resuming.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">What is the difference between single-subscription and broadcast streams?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Single-subscription streams support one listener, while broadcast streams can support multiple listeners.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">What is FutureBuilder in Flutter?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><code>FutureBuilder<\/code> builds widgets based on snapshots of a future&#8217;s completion state.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">What is StreamBuilder in Flutter?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><code>StreamBuilder<\/code> builds widgets based on snapshots of events from a stream.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Should I use FutureBuilder or StreamBuilder?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Use <code>FutureBuilder<\/code> for a single asynchronous result and <code>StreamBuilder<\/code> for a sequence of updates.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Can I use async\/await inside initState()?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">You cannot declare <code>initState()<\/code> itself as <code>async<\/code> because it must return <code>void<\/code> synchronously.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">You can start an asynchronous method from <code>initState()<\/code>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">How do I avoid setState after dispose?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Check <code>mounted<\/code> before updating state from an asynchronous callback, and manage cancellation where supported.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">How can I handle API errors in Flutter?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Use structured exception handling, meaningful error states, retry actions, and appropriate logging.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Does async\/await make CPU-heavy operations faster?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">No. CPU-heavy synchronous work can still block the isolate. Consider isolates for substantial computation.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Is asynchronous programming important for Flutter developers?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Yes. Networking, databases, device communication, file operations, and many framework APIs rely on asynchronous programming.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">22. Conclusion<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Asynchronous programming is a fundamental part of professional Dart and Flutter development.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It enables applications to remain responsive while performing operations such as networking, database access, file processing, and real-time event handling.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In this tutorial, we explored Dart&#8217;s event loop, <code>Future<\/code>, <code>async<\/code>, <code>await<\/code>, concurrent operations, timeouts, and structured error handling.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">We also learned how streams deliver multiple asynchronous events, how to create generators using <code>async*<\/code> and <code>yield<\/code>, and how to manage stream subscriptions safely.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Finally, we built a Flutter Live Task Dashboard demonstrating <code>FutureBuilder<\/code>, <code>StreamBuilder<\/code>, concurrent data loading, live updates, retry functionality, and automated tests.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The key lesson is simple:<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Use Future for one asynchronous result, Stream for multiple asynchronous events, and always design for errors, lifecycle changes, and cancellation.<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">These principles will help you build reliable Flutter applications that communicate with APIs, databases, Bluetooth devices, and other asynchronous data sources.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">What&#8217;s Next in the Flutter Tutorials Series?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Flutter Article 16: Dart Isolates and Concurrency Explained \u2014 Isolate.run, compute, Message Passing &amp; Flutter Performance (2026 Guide)<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In the next tutorial, we&#8217;ll explore CPU-bound operations, Dart isolates, background computation, message passing, <code>Isolate.run<\/code>, Flutter&#8217;s <code>compute()<\/code> helper, and performance optimization with practical examples.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Continue learning Flutter and Dart:<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Moiks Developer Blog:<\/strong> <a href=\"https:\/\/moiks.com\/blog\/\">https:\/\/moiks.com\/blog\/<\/a><\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Official Documentation and References<\/h2>\n\n\n\n<ol start=\"1\" class=\"wp-block-list\">\n<li>Dart Asynchronous Programming \u2014 <a href=\"https:\/\/dart.dev\/language\/async\" target=\"_blank\" rel=\"noopener\">https:\/\/dart.dev\/language\/async<\/a><\/li>\n\n\n\n<li>Dart Futures and Error Handling \u2014 <a href=\"https:\/\/dart.dev\/libraries\/async\/futures-error-handling\" target=\"_blank\" rel=\"noopener\">https:\/\/dart.dev\/libraries\/async\/futures-error-handling<\/a><\/li>\n\n\n\n<li>Dart Streams \u2014 <a href=\"https:\/\/dart.dev\/libraries\/async\/using-streams\" target=\"_blank\" rel=\"noopener\">https:\/\/dart.dev\/libraries\/async\/using-streams<\/a><\/li>\n\n\n\n<li>Dart Concurrency \u2014 <a href=\"https:\/\/dart.dev\/language\/concurrency\" target=\"_blank\" rel=\"noopener\">https:\/\/dart.dev\/language\/concurrency<\/a><\/li>\n\n\n\n<li>Flutter FutureBuilder \u2014 <a href=\"https:\/\/api.flutter.dev\/flutter\/widgets\/FutureBuilder-class.html\" target=\"_blank\" rel=\"noopener\">https:\/\/api.flutter.dev\/flutter\/widgets\/FutureBuilder-class.html<\/a><\/li>\n\n\n\n<li>Flutter StreamBuilder \u2014 <a href=\"https:\/\/api.flutter.dev\/flutter\/widgets\/StreamBuilder-class.html\" target=\"_blank\" rel=\"noopener\">https:\/\/api.flutter.dev\/flutter\/widgets\/StreamBuilder-class.html<\/a><\/li>\n\n\n\n<li>Flutter Testing Overview \u2014 <a href=\"https:\/\/docs.flutter.dev\/testing\/overview\" target=\"_blank\" rel=\"noopener\">https:\/\/docs.flutter.dev\/testing\/overview<\/a><\/li>\n\n\n\n<li>Flutter App Architecture \u2014 <a href=\"https:\/\/docs.flutter.dev\/app-architecture\" target=\"_blank\" rel=\"noopener\">https:\/\/docs.flutter.dev\/app-architecture<\/a><\/li>\n\n\n\n<li>DartPad \u2014 <a href=\"https:\/\/dartpad.dev\/\" target=\"_blank\" rel=\"noopener\">https:\/\/dartpad.dev\/<\/a><\/li>\n<\/ol>\n\n\n\n<p class=\"wp-block-paragraph\"><em>Moiks Developer Blog \u2014 Practical Flutter, Dart, Android, and iOS development tutorials.<\/em><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Learn asynchronous programming in Dart with Future, async, await, Future.wait, Streams, subscriptions, and error handling. Build a practical Flutter live task dashboard using FutureBuilder and StreamBuilder, with loading states, retry logic, cancellation, and automated tests.<\/p>\n","protected":false},"author":1,"featured_media":504,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"iawp_total_views":0,"footnotes":""},"categories":[353,397],"tags":[544,536,538,541,394,539,540,537,543,542,545],"class_list":["post-503","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-flutter-tutorials","category-dart-programming","tag-asynchronous-programming-in-dart","tag-dart-async-await","tag-dart-error-handling","tag-dart-future","tag-dart-programming","tag-dart-streams","tag-flutter-async-programming","tag-future-wait","tag-futurebuilder","tag-streambuilder","tag-streamsubscription"],"_links":{"self":[{"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/posts\/503","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/comments?post=503"}],"version-history":[{"count":1,"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/posts\/503\/revisions"}],"predecessor-version":[{"id":505,"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/posts\/503\/revisions\/505"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/media\/504"}],"wp:attachment":[{"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/media?parent=503"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/categories?post=503"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/tags?post=503"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}