首页 > 解决方案 > Flutter中解析Json列表

问题描述

如何在 Flutter 的 ListTile>FutureBuilder 中解析这个?我想在 ListTile 中显示 ListTile 标题应该只是 docType。下面是我的url响应模型类。我通过我得到的响应从在线转换器工具生成了这个模型类

//要解析这个JSON数据,做

import 'dart:convert';

final truckDocuments = truckDocumentsFromJson(jsonString);

List<TruckDocuments> truckDocumentsFromJson(String str) =>
    List<TruckDocuments>.from(
        json.decode(str).map((x) => TruckDocuments.fromJson(x)));

String truckDocumentsToJson(List<TruckDocuments> data) =>
    json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

class TruckDocuments {
  TruckDocuments({
    this.id,
    this.docType,
    this.docFor,
    this.expDate,
    this.expMonth,
    this.sortOrder,
    this.required,
    this.status,
    this.alert,
    this.hasExpiryDate,
    this.selected,
  });

  int id;
  String docType;
  String docFor;
  int expDate;
  int expMonth;
  int sortOrder;
  bool required;
  int status;
  String alert;
  bool hasExpiryDate;
  bool selected;

  factory TruckDocuments.fromJson(Map<String, dynamic> json) => TruckDocuments(
        id: json["id"],
        docType: json["docType"],
        docFor: json["docFor"],
        expDate: json["expDate"],
        expMonth: json["expMonth"],
        sortOrder: json["sortOrder"],
        required: json["required"],
        status: json["status"],
        alert: json["alert"],
        hasExpiryDate: json["hasExpiryDate"],
        selected: json["selected"],
      );

  Map<String, dynamic> toJson() => {
        "id": id,
        "docType": docType,
        "docFor": docFor,
        "expDate": expDate,
        "expMonth": expMonth,
        "sortOrder": sortOrder,
        "required": required,
        "status": status,
        "alert": alert,
        "hasExpiryDate": hasExpiryDate,
        "selected": selected,
      };
}

标签: jsonflutterdartmodeljsonparser

解决方案


不确定,但这可能对你有用。类 ListViewOfTrack 扩展 StatelessWidget { const ListViewOfTrack({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: FutureBuilder(
        future: Future.delayed(Duration(seconds: 1)), //Retrieving data

        builder: (BuildContext context, AsyncSnapshot snapshot) {
          if (snapshot.hasData) {
            //snapshot contains json data. Pass that to turckDocumentsFromJson
            var response = snapshot.data;
            final truckDocuments = truckDocumentsFromJson(response.body);
            return ListView.builder(
              itemBuilder: (context, index) {
                return ListTile(
                  title: truckDocuments[index].docType,
                );
              },
            );
          }
          return Center(
            child: CircularProgressIndicator(),
          );
        },
      ),
    );
  }
}

推荐阅读