如何在Flutter中检索json数据元素到列表view.builder中? [英] How to retrieve json data elements in to list view.builder in flutter?

查看:50
本文介绍了如何在Flutter中检索json数据元素到列表view.builder中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

然后绑定Json数据:

Then bind the Json data:

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

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

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

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

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

JSON数据

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

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

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

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

推荐答案

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

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

这篇关于如何在Flutter中检索json数据元素到列表view.builder中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆