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

Dart语言中如何遍历Map列表并返回对应值?字典类实现遇阻

Dart Dictionary类实现:修复单词查询逻辑

原代码存在的问题

  1. add方法被定义为构造方法,但调用时使用了静态调用方式,逻辑不匹配
  2. 类中的term和definition实例变量属于冗余定义,实际操作的是全局wordList
  3. get方法返回类型错误(当前为void),且未实现核心查询逻辑

修正后的完整代码

List<Map<String, String>> wordList = [];

void main() {
  Dictionary.add({'term': 'apple', 'definition': 'red'});
  Dictionary.add({'term': 'banana', 'definition': 'yellow'});

  print(Dictionary.get('apple')); // 输出'red'
  print(Dictionary.get('orange')); // 输出null
}

class Dictionary {
  static void add(Map<String, String> word) {
    // 加入参数校验,避免非法空值存入列表
    if (word['term'] != null && word['definition'] != null) {
      wordList.add(word);
    }
  }

  static String? get(String targetTerm) {
    // 使用firstWhere遍历列表,找到第一个匹配term的元素
    final matchedWord = wordList.firstWhere(
      (word) => word['term'] == targetTerm,
      orElse: () => {}, // 找不到时返回空Map
    );
    return matchedWord['definition'];
  }
}

关键逻辑说明

  • add改为静态方法,符合调用方式,同时加入简单校验避免无效数据
  • get方法通过List.firstWhere实现查询:遍历列表匹配目标单词,找不到时返回空Map,最终返回对应的释义(无匹配则返回null)
  • 如果业务确保查询的单词一定存在,可改为强制返回String(需处理空值断言,找不到时会抛出异常):
static String get(String targetTerm) {
  final matchedWord = wordList.firstWhere((word) => word['term'] == targetTerm);
  return matchedWord['definition']!;
}

更优实现方案

字典场景更适合直接用Map<String, String>存储(查询效率从O(n)提升到O(1)),代码更简洁:

Map<String, String> dictionary = {};

void main() {
  Dictionary.add('apple', 'red');
  Dictionary.add('banana', 'yellow');

  print(Dictionary.get('apple')); // 输出'red'
}

class Dictionary {
  static void add(String term, String definition) {
    dictionary[term] = definition;
  }

  static String? get(String term) {
    return dictionary[term];
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 14:42:51