Flutter: Async call inside FutureBuilder

Issue

I have an asynchronous call which gets me a list of objects from which I generate a ListView with ListView.builder. Each object has a property called usedId which is an integer.


I’m trying to get a user object based in its id.


This is my FutureBuilder:

FutureBuilder<MyObjects>(
    future: getMyObjects(),
    builder: (context, snapshot) {
      if (snapshot.hasError) return Text('Error ${snapshot.error}');
      if (snapshot.connectionState != ConnectionState.done) return Center(child: CircularProgressIndicator());

        return ListView.builder(
            itemCount: snapshot.data.content.length,
            itemBuilder: (BuildContext context, int index) {
                // Get user by its id
                User user;
                Future<User> futureUser = QuestionRestApi.getStatistics(snapshot.data.userId);
                futureUser.then((data) {
                    print(user);
                    user = data;
                });
                
                return Text('Username: user.username');
            }
        )
    }
);

My user is printed inside the then() function, but because it has to wait for it. I just don’t know how to handle async call inside async call.

Solution

You need multiple FutureBuilders:

FutureBuilder<MyObjects>(
    future: getMyObjects(),
    builder: (context, snapshot) {
      if (snapshot.hasError) return Text('Error ${snapshot.error}');
      if (snapshot.connectionState != ConnectionState.done) return Center(child: CircularProgressIndicator());
        return ListView.builder(
          itemCount: snapshot.data.content.length,
          itemBuilder: (BuildContext context, int index) {
            return FutureBuilder<User>(
                future: QuestionRestApi.getStatistics(snapshot.data.userId),
                  builder: (context, userSnapshot) {
                    return Text('Username: ${userSnapshot.data.username}');
                 }
            }
        )
    }
);

This would call QuestionRestApi.getStatistics for each list item (so multiple requests)

But if you only need to retrieve this User once:
Can I use multiple method on a future builder?

Answered By – Nuts

Answer Checked By – Pedro (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *