Flutter代码报错:Map键值空安全问题与分数更新需求
问题解决:Dart嵌套结构中获取选中选项的score并更新分数
错误原因分析
- 你直接对
_question[_index]['Answer']调用['score'],但'Answer'对应的是答案列表,不是单个答案Map,必须指定选中选项的索引才能拿到对应的score值。 - Dart空安全机制要求处理可能的null值,比如键不存在、列表为空、索引越界这些情况,不能直接无条件调用
[]。
修正后的代码
var _finalscore = 0; var _index = 0; final _question = [ { 'Questionkey': "which cryptocurrency do you like", 'Answer': [ {'text': 'bitcoin', 'score': 1}, {'text': 'etherium', 'score': 0} ] }, { 'Questionkey': "and why do you like that?", 'Answer': [ {'text': 'stable', 'score': 1}, {'text': 'i don\'t know actually', 'score': 0} ] }, ]; // 传入用户选中的选项索引 void _printanswer(int selectedAnswerIndex) { final currentQuestion = _question[_index]; final answers = currentQuestion['Answer'] as List?; // 确保答案列表存在,且选中索引在合法范围内 if (answers != null && selectedAnswerIndex >= 0 && selectedAnswerIndex < answers.length) { final selectedAnswer = answers[selectedAnswerIndex] as Map?; // 安全获取score,为空时默认取0 final score = selectedAnswer?['score'] as int? ?? 0; if (score == 1) { _finalscore += 1; } } setState(() { _index++; }); }
代码说明
- 给
_printanswer方法新增selectedAnswerIndex参数,用来接收用户点击的选项序号(比如第一个选项传0,第二个传1)。 - 每一步都做了非空和合法性检查,避免空指针和索引越界错误。
- 用
?? 0处理score为null的情况,保证逻辑不会因为数据异常中断。
内容的提问来源于stack exchange,提问作者lional messi
相关产品推荐
相关产品推荐

