How to Map Flutter JSON Strings from List?

前端 未结 3 812
遥遥无期
遥遥无期 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:50

    I would Love to share this and some expert can also please improve this codes, After alot of hours have battle with it.

    Model Class

    class Testimony{
        String fullname;
       String testimony;
    
       Testimony({this.fullname,
         this.testimony}); 
    
        factory Testimony.fromJson(Map<String, dynamic> json) => new Testimony(
          fullname: json['fullname'] as String,
           testimony: json['testimony'] as String,  
             );
    
             }
    

    API CLASS

    List<Testimony> ToListandMap (String responseBody) {
     Map data = json.decode(responseBody);
        var videos = data['testimonies']; //returns a List of Maps
      final casting =  videos.cast<Map<String, dynamic>>();
       return casting.map<Testimony>((json) => Testimony.fromJson(json)).toList();
        }
    
    Future<List<Testimony>> fetchTestimonies(http.Client client) async {
           final response = await client.get('https://tryjambcbt.com/api/testimonies');
    
             return ToList(response.body);
             }
    

    MainWidget for UI

    FutureBuilder<List<Testimony>>(
        future: fetchTestimonies(http.Client()),
        builder: (context, snapshot) {
          if (snapshot.hasError) print(snapshot.error);
          return snapshot.hasData
              ? TestimonyList(testimony: snapshot.data)
              : Center(child: CircularProgressIndicator());
        },
      ),
    

    Widget

    class TestimonyList extends StatelessWidget {
    final List<Testimony> testimony;
    
    TestimonyList({Key key, this.testimony}) : super(key: key);
    
      @override
     Widget build(BuildContext context) {
      return ListView.builder(
        physics: BouncingScrollPhysics(),
        padding: EdgeInsets.only(bottom: 10),
        shrinkWrap: true,
        scrollDirection: Axis.vertical,
        itemCount: testimony.length,
        itemBuilder: (context, index) {
        return Padding(
          padding: EdgeInsets.only(right: 10),
          child: Text(testimony[index].testimony)
           );
          },
        );
       }
      }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-02-10 12:07

    It looks like data['items'] is a List (i.e. a JSON Array), not a Map.

    You can use list comprehension methods to help here:

    final items = (data['items'] as List).map((i) => new CardInfo.fromJson(i));
    for (final item in items) {
      print(item.id);
    }
    
    0 讨论(0)
提交回复
热议问题