Running an asynchronous function in initState – what type of execution will be?

Since the initState function is executed synchronously, how will load() be executed in this case – asynchronously or synchronously?

How to be sure of this?

class _ExampleState extends State<Example> {

  @override
  void initState() {
    super.initState();

    load(); //will it run synchronously or asynchronously?
  }

  Future<void> load() async {
    debugPrint('loading');
    await doIt();
  }
  ...

p.s. I was always surprised that if you ask some kind of rubbish, then immediately a lot of answers, because they are easy to answer and earn points. And if you ask something that is not quite obvious, then the question will sooner be underestimated, since it is not entirely clear what is the matter …

>Solution :

The short answer is it will be performed asynchronously. So Here is some code I’ll use to explain.

class MyStateful extends StatefulWidget {
  const MyStateful({super.key});

  @override
  State<MyStateful> createState() => _MyStatefulState();
}

class _MyStatefulState extends State<MyStateful> {
  @override
  void initState() {
    super.initState();

    load();
  }

  Future<void> load() async {
    debugPrint("loading");
    await doIt();
  }

  @override
  Widget build(BuildContext context) {
    return const Center(
      child: Text("Hello"),
    );
  }
}

Future<void> doIt() async {
  await Future.delayed(const Duration(seconds: 5));
  debugPrint("done");
}

When the MyStateful Widget is built, the initState() function is executed. But because the load() function inside initState() function has no await, load() function will be executed but the rendering(building) of the widget will start before the result of load(). So the debugPrint("done"); will be executed after the widget is rendered.

This solution has no problem for cases where the result of the future function is not needed for building the widget. ex) logging data

This solution has problems where the result is needed for building the widget. ex) showing data from a database.
In this case, consider using FutureBuilder!

Leave a Reply