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

Flutter代码报错:Map键值空安全问题与分数更新需求

问题解决:Dart嵌套结构中获取选中选项的score并更新分数

错误原因分析

  1. 你直接对_question[_index]['Answer']调用['score'],但'Answer'对应的是答案列表,不是单个答案Map,必须指定选中选项的索引才能拿到对应的score值。
  2. 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 14:01:05