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()])

Share:
186
Adnan Alshami
Author by

Adnan Alshami

Updated on December 23, 2022

Comments

  • Adnan Alshami
    Adnan Alshami over 1 year

    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 and https://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
      Yashwardhan Pauranik over 3 years
      You 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
      Adnan Alshami over 3 years
      Yes, post model has the user id
  • Adnan Alshami
    Adnan Alshami over 3 years
    hmmm. 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
    meursault334 over 3 years
    Given 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.