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

Flutter报错Null check operator used on a null value求助排查

问题排查:Null check operator used on a null value

核心原因:运算符优先级错误

你遇到的空指针错误不是来自scores[section],而是Dart运算符优先级导致的逻辑偏差:??的优先级低于/,所以你的代码行:

percent = (scores[section] ?? 0 / totalPerSection[section]!) * 100;

实际执行顺序是先计算0 / totalPerSection[section]!,再执行scores[section] ?? 计算结果。当totalPerSection[section]为null时,totalPerSection[section]!的强制解包就会触发Null check operator used on a null value错误,和scores[section]是否有值完全无关。

而你在getSectionScore里的scores[section] ?? 0没问题,是因为这里没有涉及更低优先级的运算符,空值兜底逻辑能正确执行。

修复方案

给scores[section] ?? 0加上括号,确保先完成空值兜底,再执行除法运算:

percent = ((scores[section] ?? 0) / totalPerSection[section]!) * 100;

额外风险提醒

另外,你在getSectionPtsPoss和修复后的代码中都用了totalPerSection[section]!强制解包,这意味着如果totalPerSection中不存在对应section的键,依然会触发空指针。建议给totalPerSection也加上空值兜底,避免崩溃:

// 比如用1避免除以0,或者根据业务逻辑设置合理默认值
(totalPerSection[section] ?? 1)

如果业务上totalPerSection[section]不允许为null,也可以先做显式判断:

try {
  final score = scores[section] ?? 0;
  final total = totalPerSection[section];
  if (total == null || total == 0) {
    percent = 0; // 或者抛出符合业务逻辑的异常
  } else {
    percent = (score / total) * 100;
  }
} on NoSuchMethodError catch (_) { }

内容的提问来源于stack exchange,提问作者blackbird

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 18:55:16