Home > Net >  How to combine two api response data into single list of data
How to combine two api response data into single list of data

Time:07-26

I am having two set of apis. Which gives me a list of array of data.

For ex:

First api returns "postData". Second api return "promotionData".

Now i have to list the postdata in a page. I used Listview.builder to show all the postData api response data.

Now i have promotionData which return another set of json list of data.

The actual output i need is i want to display the five data of postData and then in between i have to show promotionData details and then postData details.

This is similar to FB and Twritter. Where we can see 5 posts and one promoAdd data.

How can i do this. Please help fnz.....

CodePudding user response:

Just build a combined list. Something like:

// replace String to actual object that you are using
List<String> combinedList = [];
int promotionIndex = 0;
for (var postIndex=0 ; postIndex < postData.length ; postIndex  ) {
    if (postIndex > 0 && postIndex % 5 == 0) {
         combinedList.add(promotionData[promotionIndex]);
         promotionIndex  ;
    }
    combinedList.add(postData[postIndex]);
}

CodePudding user response:

If you don't want to use a combinedList, you could change your ListView.builder instead:

// variable in your widget
int _promotionIndex = 0;
...
ListView.builder(
  itemCount: postData.lenght   promotionData.length,
  itemBuilder: (context, index) {
    if((index   1) % 5 == 0) { //important line
     // return your PromotionWidget here
     // access it with promotionData[promotionIndex]
     promotionIndex  ;
    }
    // return your PostWidget here
  },
)

(index 1) % 5 == 0 provides the functionality you need, as it check whether the index is divisible by 5.

  • Related