Flutter _CastError修复:Null无法转为List<Map<String, dynamic>?>
修复Flutter _CastError:type 'Null' is not a subtype of type 'List<Map<String, dynamic>?> in type cast'
问题原因
你的代码写于Flutter空安全特性全面启用之前,现在默认开启空安全后,questions[questionIndex]['answers']可能返回null,而你直接用as List<Map<String, dynamic>?>强制转换null,就会触发这个类型转换错误。
修复方案
添加空安全兼容的类型转换
将原代码中强制转换的部分,改为可空类型转换并提供默认空列表,避免null直接转换报错:...((questions[questionIndex]['answers'] as List<Map<String, dynamic>?>?) ?? []).map((answer) { // 原映射逻辑 }).toList()避免强制解包空值
你用answer!强制解包可能为null的answer,这会引发另一个空指针错误,建议添加空判断:return answer != null ? Answer(() => answerQuestion(answer['score']), answer['text'] as String) : const SizedBox.shrink();校验数据源合法性
检查你的questions数据源,确保每个question的answers字段确实是List类型,无null值。若数据源存在异常,优先修正数据源,再在代码中做兼容处理。优化函数类型声明(可选)
将模糊的Function answerQuestion改为明确的类型(假设score是int类型),符合空安全规范:final void Function(int) answerQuestion;
修复后完整代码
import './question.dart'; import './answer.dart'; class Quiz extends StatelessWidget { final List<Map<String, dynamic>> questions; final int questionIndex; final void Function(int) answerQuestion; const Quiz({ super.key, required this.questions, required this.answerQuestion, required this.questionIndex, }); @override Widget build(BuildContext context) { return Column( children: [ Question( questions[questionIndex]['questionText'] as String, ), ...((questions[questionIndex]['answers'] as List<Map<String, dynamic>?>?) ?? []).map((answer) { return answer != null ? Answer(() => answerQuestion(answer['score'] as int), answer['text'] as String) : const SizedBox.shrink(); }).toList(), ], ); } }
内容的提问来源于stack exchange,提问作者Ankit Kumar
相关产品推荐
相关产品推荐

