如何将我的地图对象数据转换为列表



我正试图将Map对象更改为Flutter中的列表,但我根本不知道在哪里更改代码。我试图在图表文件和模型文件中更改它,但它总是给我错误。

以下是我的API的样子:

{
"1": [
{
"tracked_at": "2020-11-29T17:33:42.000000Z",
"fuel": 71.05,
"level": 2.4867087,
"volume": 41671.1
},
{
"tracked_at": "2020-11-30T01:41:41.000000Z",
"fuel": 70.04,
"level": 2.451534,
"volume": 41031.36
},
{
"tracked_at": "2020-11-30T01:44:05.000000Z",
"fuel": 68.47,
"level": 2.396358,
"volume": 40015.56
},
{
"tracked_at": "2020-11-30T01:46:47.000000Z",
"fuel": 66.89,
"level": 2.341182,
"volume": 38985.96
},
{
"tracked_at": "2020-11-30T01:49:23.000000Z",
"fuel": 65.31,
"level": 2.286006,
"volume": 37943.9
},
],
"2": [
{
"tracked_at": "2020-11-30T01:37:17.000000Z",
"fuel": 70.71,
"level": 2.47481784,
"volume": 41455.55
},
{
"tracked_at": "2020-11-30T01:42:29.000000Z",
"fuel": 69.06,
"level": 2.41724224,
"volume": 40401.74
},
{
"tracked_at": "2020-11-30T01:44:33.000000Z",
"fuel": 67.52,
"level": 2.3630534400000003,
"volume": 39395.65
}
]
}

我的模型是这样的:

import 'dart:convert';
Map<String, List<TankPing>> tankPingFromJson(String str) => Map.from(json.decode(str)).map((k, v) => MapEntry<String, List<TankPing>>(k, List<TankPing>.from(v.map((x) => TankPing.fromJson(x)))));
String tankPingToJson(Map<String, List<TankPing>> data) => json.encode(Map.from(data).map((k, v) => MapEntry<String, dynamic>(k, List<dynamic>.from(v.map((x) => x.toJson())))));
class TankPing {
TankPing({
this.trackedAt,
this.fuel,
this.level,
this.volume,
});
DateTime trackedAt;
double fuel;
double level;
double volume;
factory TankPing.fromJson(Map<String, dynamic> json) => TankPing(
trackedAt: json["tracked_at"] == null ? null : DateTime.parse(json["tracked_at"]),
fuel: json["fuel"] == null ? null : json["fuel"].toDouble(),
level: json["level"] == null ? null : json["level"].toDouble(),
volume: json["volume"] == null ? null : json["volume"].toDouble(),
);
Map<String, dynamic> toJson() => {
"tracked_at": trackedAt == null ? null : trackedAt.toIso8601String(),
"fuel": fuel == null ? null : fuel,
"level": level == null ? null : level,
"volume": volume == null ? null : volume,
};
}

如有任何关于在哪里更改以及如何将我的地图更改为列表的帮助,我们将不胜感激。

您可以使用此网站https://javiercbk.github.io/json_to_dart/将json转换为dart。它自动为我转换。除此之外,你可以使用各种插件来实现结果。

  1. https://plugins.jetbrains.com/plugin/11460-json2dart

  2. https://marketplace.visualstudio.com/items?itemName=quicktype.quicktype

最新更新