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

Dart中如何将字符串列表转为Map列表?重复值问题排查

问题原因及解决方案

问题根源

你遇到的问题是因为所有列表元素都指向同一个Map对象。你的test Map是在循环外部创建的,每次循环只是修改这个Map的键值,然后把同一个Map的引用添加到all列表中。列表里存储的都是这个Map的内存地址,所以当循环结束后,所有位置显示的都是这个Map最终的状态(最后一次赋值的Item8)。

修正方案1:循环内创建新Map

把Map的创建放到循环内部,每次循环生成一个新的Map对象,这样列表里的每个元素都是独立的Map:

List<String> items = [
  'Item1',
  'Item2',
  'Item3',
  'Item4',
  'Item5',
  'Item6',
  'Item7',
  'Item8',
];
List all = [];

me() {
  for (int i = 0; i < items.length; i++) {
    // 每次循环初始化新的Map
    Map<String, dynamic> test = {};
    test["one"] = items[i];
    test["check"] = false;
    all.add(test);
  }
  print(all);
}

修正方案2:使用map方法(更简洁)

利用Dart的map方法直接将每个字符串转换为对应的Map,再转成列表,代码更简洁高效:

List<String> items = [
  'Item1',
  'Item2',
  'Item3',
  'Item4',
  'Item5',
  'Item6',
  'Item7',
  'Item8',
];

List all = items.map((item) => {"one": item, "check": false}).toList();
print(all);

运行以上任意一种代码,都会得到你期望的输出结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 06:15:45