Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
260 views
in Technique[技术] by (71.8m points)

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...