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

遍历Map键时编译期空检查不足,求Dart代码解决方案

Dart WordCount 空安全问题解决方案

你的代码问题出在运算符优先级:+的优先级高于??,导致resultMap[element] + 1会先执行。当resultMap[element]为null时,这一步直接触发空安全错误,根本走不到?? 0的逻辑。

下面是两种可行的修复方案:

方案1:调整运算符优先级,先处理null值

把resultMap[element]的null判断放在加法之前,用括号确保优先级:

class WordCount {
  Map<String, int> countWords(String wordle) {
    List<String> wordleCollections = wordle
        .toLowerCase()
        .split(RegExp(r",?[\s\t\n.,]"))
        .where((element) => element.isNotEmpty)
        .toList();
    var resultMap = <String, int>{};
    for (var element in wordleCollections) {
      // 先判断null,再执行加法
      resultMap[element] = (resultMap[element] ?? 0) + 1;
    }

    return resultMap;
  }
}

void main(List<String> args) {
  final wordCount = WordCount();
  print(wordCount.countWords("Joe can't tell between app, apple and a."));
}

方案2:使用Map的update方法(更简洁)

Dart的Map内置了update方法,专门处理这种"存在则更新,不存在则初始化"的场景,代码更简洁且可读性更高:

class WordCount {
  Map<String, int> countWords(String wordle) {
    List<String> wordleCollections = wordle
        .toLowerCase()
        .split(RegExp(r",?[\s\t\n.,]"))
        .where((element) => element.isNotEmpty)
        .toList();
    var resultMap = <String, int>{};
    for (var element in wordleCollections) {
      // 存在则值+1,不存在则设为1
      resultMap.update(element, (current) => current + 1, ifAbsent: () => 1);
    }

    return resultMap;
  }
}

void main(List<String> args) {
  final wordCount = WordCount();
  print(wordCount.countWords("Joe can't tell between app, apple and a."));
}

另外提一句:你的正则表达式r",?[\s\t\n.,]"可能会拆分出空字符串(比如连续标点的情况),不过你已经用where((element) => element.isNotEmpty)过滤了,这部分没问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 04:45:35