【问题标题】:The argument type 'dynamic' can't be assigned to the parameter type 'Map<String, dynamic>'参数类型“动态”不能分配给参数类型“地图<字符串,动态>”
【发布时间】:2021-12-14 16:29:18
【问题描述】:
final dataResponse = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/albums/1'));
    Album.fromJson(jsonDecode(dataResponse.body));

在启用 nullsafety 的项目上,Album.fromJson(jsonDecode(dataResponse.body)); 此代码抛出错误The argument type 'dynamic' can't be assigned to the parameter type 'Map&lt;String, dynamic&gt;'.

关注官方doc

以下用于数据建模的代码。

class Album {
  final int userId;
  final int id;
  final String title;

  Album({
    required this.userId,
    required this.id,
    required this.title,
  });

  factory Album.fromJson(Map<String, dynamic> json) {
    return Album(
      userId: json['userId'],
      id: json['id'],
      title: json['title'],
    );
  }
}

【问题讨论】:

  • fromJson(Map&lt;String, dynamic&gt; json) 改为动态fromJson(dynamic json)
  • 你的功能在我这边运行正常。
  • 您是否尝试过启用空安全的项目?

标签: flutter http dart


【解决方案1】:

你只需要转换你的 jsonDecode

Album.fromJson(jsonDecode(dataResponse.body));

到显式类型:

Album.fromJson(jsonDecode(dataResponse.body) as Map&lt;String, dynamic&gt;);

【讨论】:

    【解决方案2】:

    只需要将 (Map json) 更改为 (dynamic json)

    factory Album.fromJson(dynamic json) {
        return Album(
          userId: json['userId'],
          id: json['id'],
          title: json['title'],
        );
      }
    

    【讨论】:

    • 代码分析工具说,避免“动态”目标上的方法调用或属性访问。
    【解决方案3】:

    模型已经不错了……

    试试这个。

    final dataResponse = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/albums/1'));
    List<dynamic> list =jsonDecode(dataResponse.body);
    return list.map((e)=>Album.fromJson(e)).toList();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-24
      • 2021-08-17
      • 2019-11-15
      • 2021-12-05
      • 1970-01-01
      • 2021-10-21
      • 2021-10-13
      相关资源
      最近更新 更多