How to Map Flutter JSON Strings from List?

前端 未结 3 814
遥遥无期
遥遥无期 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 json) => new Testimony(
          fullname: json['fullname'] as String,
           testimony: json['testimony'] as String,  
             );
    
             }
    

    API CLASS

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

    MainWidget for UI

    FutureBuilder>(
        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;
    
    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)
           );
          },
        );
       }
      }
    

提交回复
热议问题