Flutter中List<dynamic>转List<List<int?>>出现类型错误如何解决?
解决List<List<int?>> JSON解析类型不匹配问题
问题原因
json.decode返回的嵌套列表均为List<dynamic>类型,直接使用List<List<int?>>.from(jsonData)时,子列表的List<dynamic>无法自动转为List<int?>,从而触发类型不匹配报错。
简单解决方法
方法一:遍历子列表显式转换
通过map遍历外层列表的每个子元素,将子列表转为List<int?>后再生成最终嵌套列表:
final jsonString = await rootBundle.loadString('lib/Permutations/$filename.json'); final jsonData = json.decode(jsonString); // json.decode是同步方法,无需await final data = (jsonData as List).map((subList) => List<int?>.from(subList)).toList();
方法二:用cast简化类型转换
确认JSON子列表元素均为int?类型(允许null)时,可直接用cast转换:
final jsonString = await rootBundle.loadString('lib/Permutations/$filename.json'); final jsonData = json.decode(jsonString); final data = (jsonData as List).map((item) => (item as List).cast<int?>()).toList();
注意事项
json.decode是同步方法,无需添加await,原代码中的await json.decode(jsonString)属于冗余写法,建议移除。- 需确保JSON文件数据结构为嵌套列表,且子列表元素仅为整数或null,否则可能触发其他类型错误。
内容的提问来源于stack exchange,提问作者Alec
相关产品推荐
相关产品推荐

