You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Dart类型不匹配错误:Sound无法赋值给Map<String, dynamic>参数

解决Dart中List转换时的类型错误:'Sound'无法赋值给'Map<String, dynamic>'

这个错误的核心原因是你在调用Sound.fromJson()时,传入的参数不是预期的Map<String, dynamic>类型,而是已经转换完成的Sound对象——通常是因为数据转换逻辑重复或者层级处理错误导致的。

常见错误场景示例

假设你的代码出现了以下逻辑混乱:

class SoundsRepository {
  final SoundsWebServices webServices;

  SoundsRepository(this.webServices);

  Future<List<Sound>> getAllSounds() async {
    // 假设webServices.fetchSounds()已经返回List<Sound>
    final sounds = await webServices.fetchSounds();
    // 错误:这里把Sound对象传给了需要Map的fromJson
    return sounds.map((sound) => Sound.fromJson(sound)).toList();
  }
}

分场景修正方案

场景1:WebServices返回原始JSON Map列表

如果你的网络层仅负责获取并返回未转换的JSON数据(List<Map<String, dynamic>>),Repository层需要完成转换:

// 网络层代码
class SoundsWebServices {
  Future<List<Map<String, dynamic>>> fetchSounds() async {
    final response = await http.get(Uri.parse('你的API地址'));
    final List<dynamic> rawData = jsonDecode(response.body);
    return rawData.cast<Map<String, dynamic>>();
  }
}

// 正确的Repository代码
class SoundsRepository {
  final SoundsWebServices webServices;

  SoundsRepository(this.webServices);

  Future<List<Sound>> getAllSounds() async {
    final soundMaps = await webServices.fetchSounds();
    // 传入Map类型参数,调用fromJson完成转换
    return soundMaps.map((map) => Sound.fromJson(map)).toList();
  }
}

场景2:WebServices已完成对象转换

如果网络层已经把JSON转成了List<Sound>,Repository直接返回即可,无需重复调用转换方法:

// 网络层代码
class SoundsWebServices {
  Future<List<Sound>> fetchSounds() async {
    final response = await http.get(Uri.parse('你的API地址'));
    final List<dynamic> rawData = jsonDecode(response.body);
    return rawData.map((map) => Sound.fromJson(map as Map<String, dynamic>)).toList();
  }
}

// 正确的Repository代码
class SoundsRepository {
  final SoundsWebServices webServices;

  SoundsRepository(this.webServices);

  Future<List<Sound>> getAllSounds() async {
    // 直接返回已转换好的列表
    return await webServices.fetchSounds();
  }
}

额外检查点

确保你的Sound类fromJson方法的参数定义正确:

class Sound {
  final String name;
  final String url;

  Sound({required this.name, required this.url});

  // 参数必须是Map<String, dynamic>类型
  factory Sound.fromJson(Map<String, dynamic> json) {
    return Sound(
      name: json['name'],
      url: json['url'],
    );
  }
}

内容的提问来源于stack exchange,提问作者ANNABA Naruto

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 19:27:22