0

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?

Kate Jo
  • 154
  • 1
  • 10

3 Answers3

1

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
  },
);
pmatatias
  • 3,491
  • 3
  • 10
  • 30
0

I think below code will work. you can use .then() function. It will execute one after another. please check this and revert

Future<int> futureInit() async {
    await functionA().then((func) async {
      await functionB();
    });
    return 0;
  }
harizh
  • 326
  • 1
  • 13
  • I tried, but it does not work. To add, it just starts building after function A starts and before it ends. So it's like [funcA start -> builder build start -> funcA end] – Kate Jo Oct 31 '22 at 04:54
0

You can delay your FutureBuilder by using:

     Future<int> futureInit() async {
      await functionA();
      await functionB();
    // Make your delay here.
    await Future.delayed(const Duration(milliseconds: 500));
    // And trigger future builder.
      return 0;
    }
D. S. Shatner
  • 40
  • 1
  • 6