Home > Software design >  How to handle reading from database when API-request hasn't finished yet to save to database in
How to handle reading from database when API-request hasn't finished yet to save to database in

Time:03-18

For my App i'm loading the link for the background-image for each screen from my API. Right after the query that downloads and saves the image-link, i'm querying the link from the database.

The problem now is, that the function isn't waiting for the download and saving to finish although i'm using await, therefor i get an empty result from the database and get an error from the imageloader.

Future<String> downloadAsset(String name) async {
    final Map<String, String> _json = {
        'mandant': Config.mandant,
        'name': name
    };
    final query = MakePost('get_app_assets', false, _json, saveAsset);
    await query.queryAPI(); // Function won't wait for this to finish
    String ret = await dbAppAssets.getText(name);  // Get link from database
    return ret;
}

I've already tried to use .then(), but the same thing happens.

This only happens initially on the first call of each screen, but how is this normally beeing handled?

I'm using riverpod with futureProviders if that matters.

CodePudding user response:

I do not know where you are using the downloadAsset function, but when you use Future on a function you should also await the function where you are using it, for example:

  Future<void> _reverseScrollToTopAnimation() async {
    await controller!.reverse();
    _showBackToTopButton = false; // hide the back-to-top button
  }

then, wherever you call it you should also await that function:

await _reverseScrollToTopAnimation();

If not the function will act as a synchronous operation even though you are using await inside the function.

  • Related