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

Dart如何在Map集合的指定键值对之间插入新对象

Dart 实现Map指定键后插入新键值对

Dart 默认的Map实现为LinkedHashMap,本身按照插入顺序维护键的排列顺序,没有提供原生的指定位置插入接口,要在已定位的锚点键"hi"的相邻后续位置插入新键值,可通过以下方式实现:

实现逻辑

由于LinkedHashMap的顺序由插入顺序决定,要在中间位置插入新键值,只需要先把锚点键之后的所有原有键值对临时缓存,删除这些后续键值后先插入新键值,再把缓存的原有后续键值重新放回Map即可。

可直接运行的示例代码

void main() {
  Map<String, double> list = {};
  list.putIfAbsent("hello", () => 2.0);
  list.putIfAbsent("hi", () => 5.0);
  list.putIfAbsent("world", () => 8.0);

  // 锚点键、待插入的键值
  const anchorKey = "hi";
  const insertKey = "hi there";
  const insertValue = 12.0;

  // 插入逻辑
  if (list.containsKey(anchorKey) && !list.containsKey(insertKey)) {
    // 取出锚点位置之后的所有键值对缓存
    final keyIndexList = list.keys.toList();
    final anchorIndex = keyIndexList.indexOf(anchorKey);
    final tempCache = list.entries.skip(anchorIndex + 1).toList();
    
    // 删除原有后续键值对
    for (final entry in tempCache) {
      list.remove(entry.key);
    }
    
    // 插入新键值
    list[insertKey] = insertValue;
    
    // 还原原有后续键值对
    for (final entry in tempCache) {
      list[entry.key] = entry.value;
    }
  }

  // 验证输出
  list.forEach((key, value) => print('"$key" = $value'));
}

运行后输出结果完全符合预期:

"hello" = 2.0
"hi" = 5.0
"hi there" = 12.0
"world" = 8.0

复用封装

如果需要频繁执行这类插入操作,可以封装为Map的扩展方法简化调用:

extension MapInsertExtension<K, V> on Map<K, V> {
  /// 在[anchorKey]的后面插入新的键值对[newKey]:[newValue]
  void insertAfter(K anchorKey, K newKey, V newValue) {
    if (!containsKey(anchorKey) || containsKey(newKey)) return;
    final allKeys = keys.toList();
    final anchorPos = allKeys.indexOf(anchorKey);
    final followEntries = entries.skip(anchorPos + 1).toList();
    
    followEntries.forEach((e) => remove(e.key));
    this[newKey] = newValue;
    followEntries.forEach((e) => this[e.key] = e.value);
  }
}

封装完成后直接调用即可:

list.insertAfter("hi", "hi there", 12.0);

注意:该实现无第三方依赖,兼容所有Dart运行环境,包括Flutter项目。如果锚点键本身是Map的最后一个键,逻辑也可正常运行,效果等同于在Map末尾追加新键值对。

内容的提问来源于stack exchange,提问作者Jack .T

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 21:18:27