Home > front end >  Can futures inside of Future.wait() be called sequentially?
Can futures inside of Future.wait() be called sequentially?

Time:12-14

Can futures inside of Future.wait() be called sequentially?

I have two futures which are being properly processed with a Future.wait() as part of a FutureBuilder.

These futures are actually network calls to retrieve an image (the same image), the first one retrieves the image dimensions, and the second one retrieves the actual image itself.

Id like to make sure these Future calls are actually performed in a sequence, so that one happens before the other. The actual order doesn't matter too much.

I understand that from the perspective of Future.wait(), the order doesn't necessarily matter since it will "wait" for both to finish, however it does matter for my application, since the first call to retrieve the image dimensions will actually cache the image, so that the second call isn't actually a network call but a call to the cache.

If they go out simultaneously, then theoretically there would be two network calls which I want to avoid

        FutureBuilder<List>(
          future:
          Future.wait([
            getImageDimensions(image)
            getImage(image)
          ]),
          builder: (ctx, snapshot) { ...

CodePudding user response:

Not with Future.wait, but you can simply create a Future that awaits both function calls sequentially and collects them in a list.

For example:

Future(() async => [
  await getImageDimensions(image),
  await getImage(image),
])

You can pass it to your FutureBuilder the same way:

FutureBuilder<List>(
  future: Future(() async => [
    await getImageDimensions(image),
    await getImage(image),
  ]),
  builder: (ctx, snapshot) { ... },
)
  • Related