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

Flutter空检查运算符报错:赋值键从Map取出null值

Flutter「Null check operator used on a null value」报错分析与解决

核心原因

你遇到的报错是因为totalPerSection[secCurr]返回了null,而你用!强制断言其非空导致崩溃。secCurr有值≠这个key存在于你的Map中,只要Map里没有该key对应的条目,取值就会返回null。

额外潜在问题:泛型不匹配

你定义的Map类型是Map<int, num>,但初始化时用了Map<int, int>()。虽然int是num的子类,这种写法不会直接报错,但可能引发后续类型混淆,建议统一类型:

// 统一为int类型
Map<int, int> totalPerSection = {};
// 或统一为num类型
Map<int, num> totalPerSection = {};

解决办法

  • 避免直接用!断言:先判断key是否存在再取值,比如:
    num? total = totalPerSection[secCurr];
    if (total != null) {
      // 处理total的业务逻辑
    } else {
      // key不存在时的处理,比如设置默认值
      total = 0;
    }
    
  • 确保key已提前存入Map:调用getPercentage前,确认secCurr对应的key-value已经被添加到totalPerSection中,例如:
    // 示例:提前存入数据
    totalPerSection[1] = 150;
    totalPerSection[2] = 300;
    
  • 用putIfAbsent自动设置默认值:如果希望key不存在时自动生成默认值,可以使用:
    var total = totalPerSection.putIfAbsent(secCurr, () => 0);
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 00:25:18