【问题标题】:Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'Map<dynamic, dynamic>未处理的异常:类型 'List<dynamic>' 不是类型 'Map<dynamic, dynamic> 的子类型
【发布时间】: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):

我试图找到一个有类似问题的解决方案,但无法解决。

【问题讨论】:

  • 检查响应的结构。第一个显然是地图,第二个不是。

标签: flutter dart


【解决方案1】:

Api 提供的 json 不是 Map 而是 List。

JSON 列表结构

[
  "Europe/Amsterdam",
  "Europe/Andorra",
  "Europe/Astrakhan",
....
]

这将是动态类型的列表

颤振代码

  void getTime() async {
    Response response =
        await get(Uri.parse("http://worldtimeapi.org/api/timezone/Europe"));
    List<dynamic> data = jsonDecode(response.body);
    print(data);
  }

JSON 映射结构

{
  "userId": 1,
  "id": 1,
  "title": "delectus aut autem",
  "completed": false
}

这将是类型字符串的映射,动态

颤振代码

  void getData() async {
    Response response =
        await get(Uri.parse("https://jsonplaceholder.typicode.com/todos/1"));
    Map<String, dynamic> data = jsonDecode(response.body);
    print(data);
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-03
    • 2020-05-24
    • 2019-09-26
    • 2021-05-21
    • 1970-01-01
    • 2020-11-05
    • 2020-08-20
    • 1970-01-01
    相关资源
    最近更新 更多