Search code examples
jsonflutterflutter-listview

How to retrieve json data elements in to list view.builder in flutter?


I am using below code to fetch elements of json data from the mysql server in flutter application. In which I am successful to fetch data.

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 I need to access the json elements through this in list view builder in flutter but I am not getting any idea how to access those elements

companyDetail.content

This is the JSON data to be fetched and build the list

JSON DATA

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

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

please guide me how can I get the elemental data of the JSON and get it into Listview.builder's ListTile?


Solution

  • Hope this helps this code will help to access the data inside the contents from your JSON structure and map it to variables.

    var jsonDecode = json.decode(jsonFile);
    //Decode your json file 
    
    //then map the content details to a variable.
    
    var content = jsonDecode['content'];
    // Since data inside your json eg above is a list.
    // access the first element of the list and map to a var. 
    var firstdata= content[0];
    // then map the id and name to a variable.
    String id=firstdata['id'];
    String name = firstdata['name'];
    

    use this inside the list tile inside a text widget