Home > Mobile >  How to iterate JSON objects
How to iterate JSON objects

Time:09-27

How can I iterate a json object and get it's values in dart.

Below is an Example json object that is want to get it's value.

"SomeJsonList": {
    "image": ["imageUrl1", "imageUrl2"],
    "video": ["videoUrl1", "videoUrl2"]
   }

To get the values of the image and video object as a list.

The output i am looking for:

var urlList = [];
urlList = [imageUrl1, imageUrl2,videoUrl1,
videoUrl2]

CodePudding user response:

You can merge list items using addAll as below

void main() {
  Map<String, List<String>> json = {
    "image": ["imageUrl1", "imageUrl2"],
    "video": ["videoUrl1", "videoUrl2"]
  };

  List<String>? img = json["image"];
  List<String>? vid = json["video"];
  
  List<String> list = [];
  list.addAll(img!); // better check if `img` not null instead of "!"
  list.addAll(vid!); // better check if `vid` not null instead of "!"
  //   list.addAll(xyz); // some more if needed
  
  print(list); // [imageUrl1, imageUrl2, videoUrl1, videoUrl2]
}

  • Related