[英]Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'Map<dynamic, dynamic>
I'm trying to get the data from an API and store it in a map so I can use it.我正在尝试从 API 获取数据并将其存储在地图中,以便我可以使用它。
It worked here...它在这里工作......
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"),
);
}
}
Output:输出:
I/flutter ( 8199): {userId: 1, id: 1, title: delectus aut autem, completed: false}
I/flutter ( 8199): delectus aut autem
But when I try it with the WorldTimeAPI I get an error.但是当我用WorldTimeAPI尝试它时,我得到一个错误。
Code:代码:
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"),
);
}
}
Error:错误:
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):
I have tried to find out a solution with similar questions but could not fix it.我试图找到具有类似问题的解决方案,但无法解决。
The json that the Api provides is not a Map but a List. Api提供的json不是Map而是List。
[
"Europe/Amsterdam",
"Europe/Andorra",
"Europe/Astrakhan",
....
]
This would be a List of the Type dynamic这将是类型动态的列表
void getTime() async {
Response response =
await get(Uri.parse("http://worldtimeapi.org/api/timezone/Europe"));
List<dynamic> data = jsonDecode(response.body);
print(data);
}
{
"userId": 1,
"id": 1,
"title": "delectus aut autem",
"completed": false
}
This would be a Map of the Type String,dynamic这将是类型字符串的映射,动态
void getData() async {
Response response =
await get(Uri.parse("https://jsonplaceholder.typicode.com/todos/1"));
Map<String, dynamic> data = jsonDecode(response.body);
print(data);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.