android - 在 Flutter ListView 中显示复杂的 API
问题描述
我有一个复杂的 API,它有一个 json 数组。我想在颤动的 listView 中显示 JSON 中的详细信息。以下是我的json
{
"hours": [
{
"time": "2021-03-23T00:00:00+00:00",
"waveHeight": {
"icon": 1.35,
"meteo": 1.25,
"noaa": 1.28,
"sg": 1.25
}
},
{
"time": "2021-03-23T00:00:00+00:00",
"waveHeight": {
"icon": 1.35,
"meteo": 1.25,
"noaa": 1.28,
"sg": 1.25
}
},
],
}
这是获取数据功能
void getJsonData() async {
String url2 =
'https://api.stormglass.io/v2/weather/point?lat=5.9774&lng=80.4288¶ms=waveHeight&start=2021-03-23&end2021-03-24';
String apiKey =
'sxascdsvfdyhujn5787654gb-7a54-11eb-8302-0242ac130002';
print('0');
try {
Response response = await get(Uri.parse(url2),
headers: {HttpHeaders.authorizationHeader: apiKey});
var jsonData = jsonDecode(response.body);
List data = jsonData["hours"];
data.forEach((element) {
Map obj = element;
Map wave = obj['waveHeight'];
String time = obj['time'];
print(time);
double icon = wave['icon'];
print(icon);
});
} catch (e) {
print(e);
}
}
所有 JSON 数据均已成功获取并显示在控制台中。但我想在颤动的 ListView 中显示数据。我怎样才能做到这一点?
解决方案
首先定义一个新类
class Wave {
final DateTime time;
final double icon;
final double meteo;
final double noaa;
final double sg;
Wave ({
this.time,
this.icon,
this.meteo,
this.noaa,
this.sg,
});
}
创建一个空列表
List<Wave> _data = [];
使用以下代码编辑您的代码
final _extractedData = json.decode(result.body) as Map<String, dynamic>;
List<Wave> _fetchedData = [];
_extractedData['hours'].forEach((value) {
_fetchedData.add(Wave(
time: value['time'],
icon: value['icon'],
meteo: value['meteo'],
noaa: value['noaa'],
sg: value['sg'],
));
});
_data = _fetchedData;
_data
具有从 json 接收到的新数据列表。
推荐阅读
- c# - 该平台不支持操作
- angular - MatSort 不使用 Angular 8 对 MatTable 中的数据进行排序
- svn - SVN - 在数据库中找到带有校验和“$sha1$5aa2d91900d7c70f2153f5f907946c7a339”的原始文本,但在磁盘上没有
- node.js - await 不等待执行?
- typescript - Webpack 无法编译 ts 3.7 (Optional Chaining, Nullish Coalescing)
- php - 我是 Laravel 的新手,我想将 SQL 查询转换为 laravel
- ios - SwiftUI - 如何在 SwiftUI 中弹出到特定视图?
- react-native - 如何检查字符串是否包含特定单词?
- docker - Confluent cp-kafka-connect Docker 镜像 Health is starting state
- java - 如何在不使用表单的情况下将数据从 JSP 页面传递到 Java Servlet?