【问题标题】:Flutter : display data from jsonFlutter:显示来自 json 的数据
【发布时间】:2022-01-13 08:15:11
【问题描述】:

我有一个 json 数据,我想在我的颤振应用程序中显示它,那么我如何显示来自 [bookings] 派对的数据,现在它很容易我使用这个 data[0]['now']['location'],但我很难找到一个显示来自booking 的数据的方式。有人可以帮我吗?

[
{
"now":{
"id": 28,
"userId": 6,
"bookingTypeId": 2,
"carWasherId": 26,
"buildingId": 4,
"serviceId": 1,
"packageId": 1,
"vehiculeId": 7,
"tookenPackageId": null,
"status": "ACCEPTED",
"dateTime": "2021-12-18 12:30:00",
"date": "2021-12-18",
"address": null,
"longitude": -6.7436544,
"latitude": 33.9968,
"rate": null,
"created_at": "2021-10-29T14:26:16.000000Z",
"updated_at": "2021-11-10T15:02:33.000000Z",
"location": "",
"duration": 30,
"start": "12:30",
"end": "13:00"
}
},
[
"bookings",
[
{
"id": 29,
"userId": 6,
"bookingTypeId": 1,
"carWasherId": 26,
"buildingId": 2,
"serviceId": 1,
"packageId": null,
"vehiculeId": 2,
"tookenPackageId": null,
"status": "ACCEPTED",
"dateTime": "2021-12-18 09:47:33",
"date": "2021-12-18",
"address": null,
"longitude": null,
"latitude": null,
"rate": null,
"created_at": "2021-10-29T15:03:14.000000Z",
"updated_at": "2021-11-10T15:00:25.000000Z",
"location": "",
"duration": 20,
"start": "09:47",
"end": "10:07"
},
{
"id": 30,
"userId": 6,
"bookingTypeId": 2,
"carWasherId": 26,
"buildingId": 3,
"serviceId": 1,
"packageId": 1,
"vehiculeId": 7,
"tookenPackageId": null,
"status": "ACCEPTED",
"dateTime": "2021-12-22 21:30:00",
"date": "2021-12-22",
"address": null,
"longitude": -6.7436544,
"latitude": 33.9968,
"rate": null,
"created_at": "2021-10-29T15:18:45.000000Z",
"updated_at": "2021-11-10T22:16:47.000000Z",
"location": "",
"duration": 25,
"start": "21:30",
"end": "21:55"
}
]
]
]

【问题讨论】:

  • 如果您从 API 获取数据,请参考我的回答 hereherehere 希望对您有所帮助

标签: json flutter


【解决方案1】:

创建一个命名构造函数 fromJson,它接受您的 json 数据并返回书籍列表(参见此处:https://docs.flutter.dev/development/data-and-backend/json

class Book{
  final String name;
  final String id;

  User(this.name, this.id);

  User.fromJson(Map<String, dynamic> json)
      : name = json['name'],
        id= json['id'];

  Map<String, dynamic> toJson() => {
        'name': name,
        'id': id,
      };
}

【讨论】:

    【解决方案2】:

    首先,您创建对象的模型。并创建 JSON 文件并将其放入您的项目中。

    String productData = await DefaultAssetBundle.of(context).loadString("assets/product.json");
            final jsonResult = jsonDecode(productData);
    

    您可以听到您的 JSON 数据,然后,您可以将 JSON 数据初始化到模型中。像这样

      var objProductDetails = ProductDetailsDataModel.fromJson(jsonResult);
    

    【讨论】:

      猜你喜欢
      • 2021-10-17
      • 1970-01-01
      • 1970-01-01
      • 2021-06-20
      • 2021-11-28
      • 1970-01-01
      • 1970-01-01
      • 2022-12-23
      相关资源
      最近更新 更多