【问题标题】:'List<dynamic>' is not a subtype of type 'List<Comment>'. Why can't Dart infer this type? How do I fix this?“List<dynamic>”不是“List<Comment>”类型的子类型。为什么 Dart 不能推断出这种类型?我该如何解决?
【发布时间】:2021-01-04 09:36:43
【问题描述】:

我有嵌套的 cmets。为了从 JSON 中获取它们,我有以下 fromJson() 函数:

Comment.fromJson(Map<String, dynamic> json)
      : id = json['id'],
        ...
        children = json['children'] != null
            ? json['children'].map((c) => Comment.fromJson(c)).toList()
            : null,
        ...

这会检查当前评论是否有任何子 cmets,如果有,则递归地将它们从 JSON 解析为评论。但是,当我运行它时,出现以下错误:

[ERROR:flutter/shell/common/shell.cc(214)]
Dart Unhandled Exception: 
type 'List<dynamic>' is not a subtype of type 'List<Comment>'
stack trace: #0      new Comment.fromJson (package:app/models/comment.dart:43:18)

这指向我为子级分配children = json... 的行。我是 dart 的新手,但我不明白如何映射列表,并且返回 Comment 不会让 Dart 推断列表的类型。我该如何解决?在toList() 之后添加as List&lt;Comment&gt; 不起作用。如果我在Comment.fromJson(c) 之后添加as Comment,我会得到unnecessary cast

【问题讨论】:

  • 您是从Comment.fromJson() 内部呼叫Comment.fromJson() 吗?是递归调用吗?
  • @Sisir 正确,这个Comment.fromJson() 在我的class Comment{} 里面
  • 没关系。但是您是从同一方法内部调用该方法吗?或者是拼写错误。
  • @Sisir 是的,来自同一个方法。它是递归的。

标签: dart


【解决方案1】:

Dart 无法从 json['children'].map(...).toList() 推断出任何内容,因为 json['children'] 的类型为 dynamic,因此它不知道 .map 调用在运行时将解析到什么。

在运行时,由于调用.map 时没有显式类型,因此最终调用.map&lt;dynamic&gt;(...),然后.toList() 返回List&lt;dynamic&gt;

试试:

  • 显式使用.map&lt;Comment&gt;(...)
  • 铸造json['children']:(json['children'] as List&lt;Map&lt;String, dynamic&gt;&gt;).map(...)。无论如何,验证这一点可能是个好主意。

【讨论】:

  • 谢谢。 .map&lt;Comment&gt;(...) 为我修好了。
猜你喜欢
  • 2020-06-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-29
  • 2023-01-08
  • 2021-06-24
  • 2021-07-06
  • 2021-02-17
相关资源
最近更新 更多