I have a Json file like below and already parsed and Model passed to next page. What I am trying to generate a list based on YoutubeId
on the next page.
final videoID;
final CourseLessonDetailsData courseLessons;
final CourseLessonsModel courseLessonsModel;
Json response:
{
"CourseLessonDetailsData": [
{
"request_status": "Successful",
"ID": "24973",
"LessonContentDetails": [
{
"TopicInfo": [
{
"ID": "2764",
"CourseCode": "DTS",
}
],
"PreAssessment": [],
"Video": [
{
"YoutubeId": "yt_id1",
}
],
}
],
}
{
"request_status": "Successful",
"ID": "24974",
"LessonContentDetails": [
{
"TopicInfo": [
{
"ID": "2765",
"CourseCode": "DTS",
}
],
"PreAssessment": [],
"Video": [
{
"YoutubeId": "yt_id2",
}
],
}
],
}
{
"request_status": "Successful",
"ID": "24975",
"LessonContentDetails": [
{
"TopicInfo": [
{
"ID": "2766",
"CourseCode": "DTS",
}
],
"PreAssessment": [],
"Video": [
{
"YoutubeId": "yt_id3",
}
],
}
],
}
]
},
Using the following code, I’m able to parse the first item but not able to get the rest.
for(var data in widget.courseLessonsModel.courseLessonDetailsData as Iterable){
youTubeIds.add(widget.courseLessons.lessonContentDetails!.first.video!.first.youtubeId);
}
print(youTubeIds);
Here’s how to my list
is printed.
[yt_id1, yt_id1, yt_id1]
while my expected output is
[yt_id1, yt_id2, yt_id3]
I’m aware that I’m using first
so only the first option will be retrieved. How should I retrieve all and what to replace with first
?
2
Answers
As mentioned in the question, I was trying to create a list from the Json model. I achieved this by creating an empty list first then add elements in it when I created my ListView.builder.
Then I passed this list to next page using the Navigator.
However, this is a terrible way to do this as I'm already passing the whole parsed object to the next page and it should be done on the next page instead of passing the list from the previous page.
UPDATE:
The above method is a poor method to create a list. A better approach is creating a list by using List.generate method in the API call function with required values. Here's how I implemented it:
Now you can use this list in any way you want.
try create a model for the items you had e.g.
this model will hold the items you had from json but first assign them
as for the data you’ve given sample
also you can try this from dart pad and copy this code from gist