1

I have a function that should be run before the building of the Widget

@override
Widget build(BuildContext context) async {

  await fetchScans();

  return CompositedTransformTarget(...);
}

How can I make the build function run async so it somehow "pauses" until the fetchScans finishes running?

Any replies or tips are much appreciated thanks!

gsan
  • 549
  • 1
  • 4
  • 14
Jack .T
  • 35
  • 8
  • You should do the `async` job in the `initState()` of the `StatefulWidget` and use 'setState()' or `FutureBuilder` to rebuild the `Widget` with the updated state. – saw May 30 '22 at 14:08
  • I guess even if you can `await`, it can block the ui thread as `Flutter` is expecting `Widget` up front while building the render tree and not `Future`. – saw May 30 '22 at 14:10
  • Also `Future build()` will not be a valid override. You will see an error on your IDE. – saw May 30 '22 at 14:12

1 Answers1

0

You cannot. You will need to handle both states, the time while the future is not yet complete and the time when the future has completed successfully. Maybe even the case when the Future has not completed successfully. The way to do this is the FutureBuilder widget.

I suggest reading What is a Future and how do I use it?

It might be a bit lengthy but it will explain everything you need to make your build function depend on a future value and it includes sample code.

nvoigt
  • 75,013
  • 26
  • 93
  • 142