【问题标题】:type 'List<dynamic>' is not a subtype of type 'List<Map<dynamic, dynamic>>'类型 'List<dynamic>' 不是类型 'List<Map<dynamic, dynamic>>' 的子类型
【发布时间】:2019-02-13 06:21:31
【问题描述】:

在 Dartlang/Flutter 中,我尝试使用 .map().toList() 创建地图列表,但收到上述错误消息。我尝试在不同的地方添加类型注释,但它们只是导致类似但不同的类型错误。

这是响应正文。

 Response body: {"data":{"logsread":[{"id":"7a2dd3b","email":"email@gmail.com"}]}}

这是代码。

http.post(url, body: read2).then((response) {
  print("Response status: ${response.statusCode}");
  print("Response body: ${response.body}");
  var tempTodos;
  tempTodos = jsonDecode(response.body)['data']['logsread']
      .map((node) => {
            'id': 0,
            'title': node['email'],
            'score': 0,
          })
      .toList();

  return Upd(model.copyWith(todoList: tempTodos));

模型类定义如下:

class Model {
  final String todo;
  final List<String> todos;
  final Map todoWithScore;
  final List<Map> todoList;

  Model(this.todo, this.todos, this.todoWithScore, this.todoList);

  Model copyWith({
    String todo,
    List<String> todos,
    Map todoWithScore,
    List<Map> todoList,
  }) =>
      Model(
        todo ?? this.todo,
        todos ?? this.todos,
        todoWithScore ?? this.todoWithScore,
        todoList ?? this.todoList,
      );
}

【问题讨论】:

  • 我能够成功运行您的地图和 toList 代码。我想问题出在你的模型类上。你能分享你的模型类结构吗?
  • 添加了模型类定义。谢谢。

标签: dart flutter


【解决方案1】:

如下图添加“as List”后试试。

tempTodos = (jsonDecode(response.body)['data']['logsread'] as List )
      .map((node) => {
            'id': 0,
            'title': node['email'],
            'score': 0,
          })
      .toList();

【讨论】:

    猜你喜欢
    • 2021-08-05
    • 2020-05-19
    • 2021-12-02
    • 2021-12-29
    • 2023-01-08
    • 2019-04-03
    • 1970-01-01
    • 2021-10-25
    • 2020-07-03
    相关资源
    最近更新 更多