Search code examples
jsonflutterflutter-listview

How to associate the json data to flutter list?


I am able to fetch the json data in flutter applicaion. Now I want to associate that data with the List.

How should I do that?

List companydetails;

var jsonResponse = json.decode(response.body);

JSON DATA

 {"error":"false","content":[
{
"id":"22","name":"Johnny",},

{"id":"23","name":"Maria",},
]
}

I need to build a list view in flutter from the fetched data.


Solution

  • You can use this model:

    class CompanyDetail {
      String error;
      List<Content> content;
    
      CompanyDetail({this.error, this.content});
    
      CompanyDetail.fromJson(Map<String, dynamic> json) {
        error = json['error'];
        if (json['content'] != null) {
          content = new List<Content>();
          json['content'].forEach((v) {
            content.add(new Content.fromJson(v));
          });
        }
      }
    
      Map<String, dynamic> toJson() {
        final Map<String, dynamic> data = new Map<String, dynamic>();
        data['error'] = this.error;
        if (this.content != null) {
          data['content'] = this.content.map((v) => v.toJson()).toList();
        }
        return data;
      }
    }
    
    class Content {
      String id;
      String name;
    
      Content({this.id, this.name});
    
      Content.fromJson(Map<String, dynamic> json) {
        id = json['id'];
        name = json['name'];
      }
    
      Map<String, dynamic> toJson() {
        final Map<String, dynamic> data = new Map<String, dynamic>();
        data['id'] = this.id;
        data['name'] = this.name;
        return data;
      }
    }
    

    Then bind the Json data:

    var companyDetail = CompanyDetail.fromJson(json.decode(response.body));
    

    Now use Content List in your ListView widget:

    companyDetail.content
    

    Example (make sure that content is not null):

    ....
    ListView.builder
      (
        itemCount: companyDetail.content.length,
        itemBuilder: (BuildContext ctxt, int index) {
         return new Text(companyDetail.content[index]);
        }
      ),
    ...