US Office

1176 Shadeville Rd, Crawfordville Florida 32327, USA

 +1 (850) 780-1313

India Office

Office No 405, Kabir Shilp, Opp. Kansar Hotel, Opp. Landmark, Kudasan, Gandhinagar, Gujarat 382421

[email protected]

What is Difference between async and async* in Dart?

What is difference between async and async in Dart

What is Difference between async and async* in Dart?

Table of Contents

When designing a mobile application using Flutter Application you might have seen two keywords async and async* so in this article we will learn about What is the Difference between async and async* in Dart.

Let’s Get Started !!!

What is async?

When users mark a function as async or async* allows it to use the async/await keyword to use a Future.

What is the difference between async and async* in Dart?

The difference between both is that async* will always return a Stream and offer some syntax sugar to emit a value through the yield keyword.

Consider a code snippet like below:

Stream foo() async* {
  for (int i = 0; i < 42; i++) {
    await Future.delayed(const Duration(seconds: 1));
    yield i;
  }
}

This function emits a value every second, that increment every time

async gives you a Future and async* gives you a Stream.

When users marks a function as async or async* allows it to use async/await keyword to use a Future.

async

async keyword to a function that does some work that might take a long time. It returns the result wrapped in the Future.

Future doSomeLongTask() async {
  await Future.delayed(const Duration(seconds: 1));
  return 42;
}

You can get that result by awaiting the Future:

main() async {
  int result = await doSomeLongTask();
  print(result); // prints '42' after waiting 1 second
}

async*

async* keyword to make a function that returns a bunch of future values one at a time. The results are wrapped in a Stream.

Stream countForOneMinute() async* {
  for (int i = 1; i <= 60; i++) {
    await Future.delayed(const Duration(seconds: 1));
    yield i;
  }
}

You can use await to wait for each value emitted by the Stream.

main() async {
  await for (int i in countForOneMinute()) {
    print(i); // prints 1 to 60, one integer per second
  }
}

Conclusion:

Hope you like this article where we have learned about What is the Difference between async and async* in Dart ?

Keep Learning !!! Keep Fluttering !!!

FlutterAgency.com is our portal Platform dedicated to Flutter Technology and Flutter Developers. The portal is full of cool resources from Flutter like Flutter Widget GuideFlutter ProjectsCode libs and etc.

FlutterAgency.com is one of the most popular online portal dedicated to Flutter Technology and daily thousands of unique visitors come to this portal to enhance their knowledge on Flutter.

Post a Comment