如何在flutter中检索json数据元素以列出list.builder?

时间:2020-08-22 15:45:59

标签: json flutter flutter-listview

我正在使用下面的代码从flutter应用程序中的mysql服务器中获取json数据的元素。我可以在其中成功获取数据。

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;
  }
}

然后绑定Json数据:

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

现在我需要在列表视图构建器中通过它访问json元素,但是我不知道如何访问那些元素

companyDetail.content

这是要获取并构建列表的JSON数据

JSON数据

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

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

请指导我如何获取JSON的元素数据并将其放入Listview.builder的ListTile中?

2 个答案:

答案 0 :(得分:1)

希望这有帮助,此代码将有助于从JSON结构访问内容内部的数据并将其映射到变量。

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'];

在文本小部件内的列表磁贴中使用此

答案 1 :(得分:0)

访问companyDetail [“ content”]