【问题标题】:NoSuchMethodError: Class 'List<dynamic>' has no instance method 'cast' with matching argumentsNoSuchMethodError:类 'List<dynamic>' 没有具有匹配参数的实例方法 'cast'
【发布时间】:2021-10-17 21:08:49
【问题描述】:

我正在尝试从我的 API 服务器获取文章,但我收到 NoSuchMethodError: Class 'List&lt;dynamic&gt;' has no instance method 'cast' with matching arguments 错误。有人知道我该如何解决吗?

 List<Article> posts;
  final response = await http.get(Uri.parse("$SERVER_IP/api/articles/?format=json"),
    headers: <String, String>{"Authorization" : "Token ${globaltoken}"},);
  final parsed = jsonDecode(utf8.decode(response.bodyBytes)).cast<String,dynamic>();
  posts = parsed.map<Article>((json) => Article.fromJSON(json)).toList();
  return posts;

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    您首先不应该使用 cast(),因为附近的操作(在本例中为 parsed.map)已经为您使用 cast() 并因此转换您想要的类型(文章)。省略 cast() 应该可以解决您的错误。

    另请参阅 dart 文档:

    1. https://dart.dev/guides/language/effective-dart/usage#dont-use-cast-when-a-nearby-operation-will-do
    2. https://dart.dev/guides/language/effective-dart/usage#avoid-using-cast

    【讨论】:

      猜你喜欢
      • 2021-11-07
      • 2019-11-20
      • 2022-11-24
      • 2020-12-19
      • 2019-06-18
      • 2022-11-21
      • 2021-02-26
      • 2020-12-20
      相关资源
      最近更新 更多