Search code examples
flutterfutureflutter-futurebuilder

Flutter - Future Builder with two async functions


I want to use FutureBuilder, but make it build after waiting for 2 async functions to end.

In the Flutter docs, it says Widget that builds itself based on the latest snapshot of interaction with a Future. So it builds after one function, not waiting for the other.

Future<int> futureInit() async {
  await functionA();
  await functionB();
  return 0;
}

My code is like this, so the future builder builds after just function A.

How can I make it wait for the both functions to end and then start building?


Solution

  • first you have to know how to handle future function. there are 2 approach. with await and with then here my article explain more about it : await vs then in Flutter

    if you want to handle 2 future function in 1 FutureBuilder,you can use Future.wait. here an old question related:https://stackoverflow.com/a/50627153/12838877

    Future<A> functionA();
    Future<B> functionB();
    FutureBuilder(
      future: Future.wait([functionA, functionB]),
      builder: (context, AsyncSnapshot<List<dynamic>> snapshot) {
        snapshot.data[0]; //functionA
        snapshot.data[1]; //functionB
      },
    );