What is Async/Await/then In Dart/Flutter?

· 5 min read
What is AsyncAwaitthen In DartFlutter
What is AsyncAwaitthen In DartFlutter

We already know What is the difference between async and async* in dart. So, in this article, we will see what is Async/Await/then in Dart/Flutter.

What is Async/Await/then In Dart/Flutter?

await is to interrupt the process flow until the async method completes. then however does not interrupt the process flow. This means that the next instructions will be executed. But it allows you to execute the code when the asynchronous method completes.

When you add the await, you explicitly say: ‘don’t go further until my future is completed.

Write your code as following to achieve the same result only with await:

Future<List<Expense>> getExpensesByFundId(int fundId) async {
    Database db = await database;

    List<Expense> expenseList = List();

    List<Map<String,dynamic>> expList = await db.query(expTable,where: '$expTable.$expFundId = $fundId');
    expList.forEach((Map<String, dynamic> expMap) {
        expenseList.add(Expense.fromMap(expMap));
    });

    return expenseList;
}

You can also choose to use only then part. But you need to ensure to call getExpensesByFundId properly afterward:

Future<List<Expense>> getExpensesByFundId(int fundId) async {
    Database db = await database;

    List<Expense> expenseList = List();

    return db.query(expTable,where: '$expTable.$expFundId = $fundId')
        .then((List<Map<String,dynamic>> expList){
      expList.forEach((Map<String, dynamic> expMap){
        expenseList.add(Expense.fromMap(expMap));
      });
    });
}

// call either with an await
List<Expense> list = await getExpensesByFundId(1);
// or with a then (knowing that this will not interrupt the process flow and process the next instruction
getExpensesByFundId(1).then((List<Expense> l) { /*...*/ });

The async and await keywords provide a declarative way to define asynchronous functions and use their results. Remember these two basic guidelines when using async and await:

  • To define an async function, add async before the function body.
  • The await keyword works only in async functions.

Here’s an example that converts main() from asynchronous to asynchronous function.

First, add the async keyword before the function body:

void main() async { ··· }

If the function has a declared return type, then update the type to be Future<T>. Here T is the type of value that the function returns. If the function doesn’t explicitly return a value, then the return type is Future<void>:

Future<void> main() async { ··· }

Now that you have an async function, you can use the await keyword to wait for a future to complete:

print(await createOrderMessage());

.Then((value) {…}) is a callback that will be called when the future completes successfully(with a value).

await createOrderMessage().then((value) {...});

Full Example of async, await, then, and Future

Future<String> createOrderMessage() async {
  var order = await fetchUserOrder();
  return 'Your order is: $order';
}

Future<String> fetchUserOrder() =>
    // Imagine that this function is
// more complex and slow.
Future.delayed(
  Duration(seconds: 2),
      () => 'Large Latte',
);

Future<void> main() async {
  print('Fetching user order...');
  print(await createOrderMessage().then((value) {
    print(value);
    return value;
  }));
}

Flutter Application is said to be a step-by-step execution of code, but this is not the case. There are many events that will trigger during the life cycle of an application, such as Click Event, Timers, etc. There must be some code that should be running in the background thread.

How to background work execute:

So, there are two Queues

  1. Microtask Queue
  2. Event Queue
  • Microtask Queue runs the code that should not execute any event (click, timer, etc). It can contain both sync and async work.
  • Event Queue runs when any external click event occurs in the application like Click event, then that block execution did inside the event loop.
  • The below diagram will explain in detail how execution will proceed.

    Async Await then flutter
    Async Await then flutter

Conclusion:

Thanks for being with us !!!

In this article, we have been what is Async/Await/then in Dart/Flutter ??

Flutter Agency 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.

Flutter Agency is one of the most popular online portals dedicated to Flutter Technology. Daily thousands of unique visitors come to this portal to enhance their knowledge of Flutter.

Leave a Reply