What is the best practice to get data from two different http end points?
186
You can try with Future.wait. refer the following documentation
https://api.dart.dev/stable/2.5.0/dart-async/Future/wait.html
Eg.
Future.wait([apiCall1(), apiCall2()])

Author by
Adnan Alshami
Updated on December 23, 2022Comments
-
Adnan Alshami 5 months
I want to fetch a list of Posts and display them in a ListView, each element of this ListView contains a title,body, and the userImage. these data will comes from two different end points from the well known jsonplaceholder
https://jsonplaceholder.typicode.com/posts
andhttps://jsonplaceholder.typicode.com/users
I have already made the Post and the User models. should I create another PostWithUser model? or what?
so what is the efficient way to combine these two http requests?
Sorry for my bad English.
-
Yashwardhan Pauranik almost 3 yearsYou kind of need to create a relation between the two tables/collections. Post model should contain a reference to user, to fetch its information.
-
Adnan Alshami almost 3 yearsYes, post model has the user id
-
-
Adnan Alshami almost 3 yearshmmm. The first request returns a list of post. Should I use
posts.forEach()
to get the user's image for each post? or there is a better way to achieve that? -
meursault334 almost 3 yearsGiven that the post model has the user id you could consider the following: 1. Use Future.wait to ensure you have both the posts and users available 2. Create a Map<int,UserInfo> userMap that will let you efficiently map the user ID's to userImage and whatever else you need to show about the user with the post (name etc). 3. Use both the userMap and the posts object to generate the either the listView of posts or to initialize a model that contains a fully baked post with the user info.