Flutter类型转换报错:Null无法转为int问题咨询
问题解答:'Null'无法转换为int类型的原因
问题描述
在SummaryItem组件中执行iconData["question-index"] as int强制类型转换时,触发错误:'type 'Null' is not a subtype of type 'int' in type cast'。尽管QuestionIdentifier组件的questionIndex参数被定义为int类型,但依然出现该报错。
错误原因
问题核心不在于QuestionIdentifier的参数定义,而在于你传入的iconData["question-index"]的值是Null:
- Dart中
as int强制转换要求被转换的值必须是int类型(或可空int的非空值),如果是Null,会直接抛出类型转换异常 - 导致
iconData["question-index"]为Null的常见场景:- 传入
SummaryItem的iconData字典中,不存在"question-index"这个键 - 该键对应的值未被正确赋值,本身就是Null
- 传入
解决方案
1. 从根源避免Null
检查生成iconData的数据源,确保每个字典都包含"question-index"键,且对应的值是合法的int类型。
2. 代码中添加Null处理
方式一:使用空值合并运算符
QuestionIdentifier( correctAnswer: isCorrectAnswer, questionIndex: (iconData["question-index"] as int?) ?? 0, // 0为默认值,可按需修改 ),
先将值转为可空int类型,再用??为Null情况提供默认值。
方式二:类型判断后赋值
QuestionIdentifier( correctAnswer: isCorrectAnswer, questionIndex: iconData["question-index"] is int ? iconData["question-index"] as int : 0, // 0为默认值,可按需修改 ),
先判断值是否为int类型,是则直接转换,否则使用默认值。
内容的提问来源于stack exchange,提问作者Dennis Castro
相关产品推荐
相关产品推荐

