首页 > 解决方案 > NoSuchMethodError:类'列表' 没有具有匹配参数的实例方法 'cast'

问题描述

我正在尝试从我的 API 服务器获取文章,但NoSuchMethodError: Class 'List<dynamic>' 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;

标签: flutterdart

解决方案


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

另请参阅飞镖文档:

  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

推荐阅读