How to Map Flutter JSON Strings from List?

前端 未结 3 819
遥遥无期
遥遥无期 2021-02-10 11:09

I\'m successfully printing my response as String from my YouTube JSON url, but when I try to serialize through the \"items\" I get the following error Unhandled exception:

3条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-10 11:52

    The following line gives you the List of items.

    var videos = data['items'];
    

    and you get the error because of this line

    for(var items in videos['snippet'])
    

    In the previous line you think you are iterating on the data inside snippet, while in fact, you are trying to iterate on the index 'snippet' inside the list of videos, which does not make sense because iterating over any list happens using integer values videos[0] , videos [1], videos [2] .. while you are passing a String 'snippet'

    You need first to iterate on your videos list item by item (each item is a Map). Store each Map in a variable. then you can access the values of snippet by myMap['snippet']

        Map data = JSON.decode(response);
        var videos = data['items']; //returns a List of Maps
        for (var items in videos){ //iterate over the list
        Map myMap = items; //store each map 
        print(myMap['snippet']);
            }
    

    See if this solves your problem.

提交回复
热议问题