zboris12

View on GitHub

Flutter: Waiting for an asynchronous operation in initState

✨ Created on 2024/6/5

Since the initState method is not asynchronous, you cannot use await within initState.
If your widget’s build does not require data from an asynchronous operation,
you can simply use the then method of the Future class.
However, if you do need data from an asynchronous operation, how can you wait for it?

[!TIP]
In my case, I use the Completer class and FutureBuilder class to address this issue.
Below is the sample code.

class _MyData {
  String? a;
  String? b;
}
class _MyHomePageState extends State<MyHomePage> {
  final _initCmp = Completer<_MyData>();

  Future<_MyData> _initState() async {
    var dat = _MyData();
    dat.a = await doSomething1();
    dat.b = await doSomething2();
    return dat;
  }

  @override
  void initState() {
    super.initState();
    _initState().then((dat) {
      _initCmp.complete(dat);
    }).catchError((err) {
      _initCmp.completeError(err);
    });
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<_MyData>(
      future: _initCmp.future,
      builder: (BuildContext context, AsyncSnapshot<_MyData> snapshot) {
        if (snapshot.hasData) {
          return SomeWidget(snapshot.data);
        } else if (snapshot.hasError) {
          return Center(
            child: Text('Error: ${snapshot.error}'),
          );
        } else {
          return const Center(
            child: Text('Awaiting result...'),
          );
        }
      },
    );
  }
}

🚗BACK