Flutter:显示来自 json 的数据

Posted

技术标签:

【中文标题】Flutter:显示来自 json 的数据【英文标题】:Flutter : display data from 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 获取数据,请参考我的回答 here 或 here 或 here 希望对您有所帮助 【参考方案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);

【讨论】:

以上是关于Flutter:显示来自 json 的数据的主要内容,如果未能解决你的问题,请参考以下文章

将 JSON 数据显示到 DataTable Flutter

关闭网页视图后,来自 Youtube 嵌入式视频的音频继续播放 - Flutter

来自 json 的 Flutter ListTile 标题名称

Flutter:如何优先显示来自 Asset 的图像,如果找不到,则显示来自 URL 的图像?

如何将数据记录到 Flutter 控制台?

Flutter:如何从 Firebase 通知负载中获取 Json 数据