What’s the difference between async and async* in Dart?

In Dart, both async and async* are used to define asynchronous functions, but they serve different purposes:

  1. async:
    • async is used to define asynchronous functions that return a single future-based result. These functions allow you to use await to pause execution until a future completes and then return the result or throw an error.
    • When you mark a function as async, it can contain await expressions inside the function body, which allows you to work with other asynchronous functions in a synchronous-style code.
    • Example of an async function:
Future<int> fetchData() async {
  await Future.delayed(Duration(seconds: 2));
  return 42;
  1. async*:
  • async* is used to define asynchronous generator functions, which are functions that can produce a sequence of values (a stream) over time.
  • Unlike regular asynchronous functions (async), async* functions use the yield keyword to produce values. The yield keyword suspends the function without exiting it, allowing the function to produce values incrementally.
  • Example of an async* generator function:
Stream<int> countStream() async* {
  for (int i = 0; i < 5; i++) {
    await Future.delayed(Duration(seconds: 1));
    yield i;

In this example, the countStream() function is an asynchronous generator that produces an integer stream with values from 0 to 4, with a delay of 1 second between each value.

In summary, the key difference between async and async* is the type of asynchronous behavior they enable:

  • async functions are used to handle single future-based results using await.
  • async* generator functions are used to produce streams of values using yield.
error: Content is protected !!