2

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.

Gabi
  • 103
  • 3
  • 9

1 Answers1

3

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?

Adelina
  • 10,915
  • 1
  • 38
  • 46