flutterasync-await

Flutter async await


I am relatively new to Flutter. I am noticing something that i was not expecting.

fetchCatalog() is an async function. I am noticing difference in below two cases:

case 1: await AppShared.fetchCatalog(forcedFetch: true);

case 2: var catalog = await AppShared.fetchCatalog(forcedFetch: true);

In case 1, code does not basically awaits. However, in case 2, it is awaiting.

Am i doing something wrong ?

Below is the call tree

void onPaymentSucess(PaymentSuccessResponse response) {
    _addCourseToSubscriptions(context, _bundleCode);
}

void _addCourseToSubscriptions(
    BuildContext context, String bundleCode) async {
        await AppShared.fetchCatalog(forcedFetch: true);
}

static Future<List<Bundle>> fetchCatalog({bool forcedFetch = false}) async {
// Fetch catalog
}

Solution

  • The first case is a scenario where you await an async function to finish but don't need its return value. The async function will finish its execution despite data fetching and global state updates because there will be no return value to capture.

    In case 2, it requires awaiting and results in storage in the catalog. The code seems to wait more visibly here but it's still waiting for the function in both scenarios.

    The function execution can proceed straightaway after the await when the result in case 1 isn't necessary.

    Hopefully, this is helpful.