How to nest Futures to wait for each other in initState

256

futureDetails: is a Future property of the StatefulWidget
Globals: contains static properties used across the app
Message: is a model with a factory method fromJson

@override
void initState() {
  super.initState();
  futureDetails = fetchIds().then((List<int> ids) => {
      Globals.userId = ids[0];
      Future.wait([
        fetchLanguage(Globals.userId),
        fetchMailboxId(Globals.userId)
      ]).then((List<dynamic> futureResult) => {
        Globals.mailboxId = futureResult[1];
        fetchMessages(Globals.mailboxId).then((Map<String, dynamic> messagesAsJson) => {
          messagesAsJson.forEach((msgJson) => Globals.messages.add(Message.fromJson(msgJson)));
        });
      });
  });
}

@override
  Widget build(BuildContext context) {
    return FutureBuilder<Widget>(
        future: futureDetails,
        builder: (BuildContext context, AsyncSnapshot<List<int>> snapshot) {
          if (snapshot.hasData) {
            // display data empty/filled
          } else if (snapshot.hasError) {
            // display error
          } else {
            // display loader
          }
        }
    );
  }
Share:
256
Ibrahim W.
Author by

Ibrahim W.

An avid software developer, seeking to immerse myself in the field of technology. My most beloved language is the one most misunderstood (Javascript), it only needs a gentle touch with a lot of understanding!

Updated on December 30, 2022

Comments

  • Ibrahim W.
    Ibrahim W. over 1 year

    At first I need to fetch some ids => one of the ids returned aka: userId is used to get mailboxId => mailboxId is used to get a list of Message Models.
    PS: each call is separate because this is how the API is built

    @override
    void initState() {
      super.initState();
      futureIds = fetchIds();
      // start those two after fetchIds() finishes
      futureMailboxId = fetchMailboxId(userId);
      futureLanguage = fetchLanguage(userId);
      // start this after fetchMailboxId(userId) finishes
      futureMessages = fetchMessages(mailboxId);
    }