【发布时间】:2021-07-25 10:34:44
【问题描述】:
我正在尝试从 API 获取数据并将其存储在地图中以便我可以使用它。
它在这里工作......
class _LoadingState extends State<Loading> {
void getData() async {
Response response =
await get(Uri.parse("https://jsonplaceholder.typicode.com/todos/1"));
Map data = jsonDecode(response.body);
print(data);
print(data["title"]);
}
@override
void initState() {
super.initState();
getData();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Text("loading screen"),
);
}
}
输出:
I/flutter ( 8199): {userId: 1, id: 1, title: delectus aut autem, completed: false}
I/flutter ( 8199): delectus aut autem
但是当我尝试使用 WorldTimeAPI 时出现错误。
代码:
class _LoadingState extends State<Loading> {
void getTime() async {
Response response =
await get(Uri.parse("http://worldtimeapi.org/api/timezone/Europe"));
Map data = jsonDecode(response.body);
print(data);
}
@override
void initState() {
super.initState();
getTime();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Text("loading screen"),
);
}
}
错误:
Restarted application in 546ms.
E/flutter ( 8199): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'Map<dynamic, dynamic>'
E/flutter ( 8199): #0 _LoadingState.getTime
package:world_time/pages/loading.dart:14
E/flutter ( 8199): <asynchronous suspension>
E/flutter ( 8199):
我试图找到一个有类似问题的解决方案,但无法解决。
【问题讨论】:
-
检查响应的结构。第一个显然是地图,第二个不是。