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

Dart中为Map重复赋值相同键后,原有键值对丢失是什么原因?

问题解答

这是Map结构的固有特性导致的:所有Map结构的键(Key)全局唯一,同一个键在一个Map实例中仅能对应一个值。
你先后两次对dn、ph两个相同的键赋值,第二次赋值操作会直接覆盖该键已有的旧值,而不是新增独立的键值对,所以最早的两组值会被后续赋值覆盖,无法保留。

如果需要保存多组同标识的内容,可以选择以下两种方案实现:

  • 方案1:为每组值设置独立的唯一键,例如使用dn1/dn2、ph1/ph2作为键
    示例代码:
    void initState() {
      super.initState();
      testMap['dn1'] = 'test name1';
      testMap['ph1'] = '4160000000';
      testMap['dn2'] = 'test name2';
      testMap['ph2'] = '7780000000';
    }
    
  • 方案2:将Map的值声明为List类型,同一个键下存储多个值
    示例代码:
    // 声明时指定Map值的类型为List<String>
    var testMap = <String, List<String>>{};
    
    void initState() {
      super.initState();
      // putIfAbsent会在键不存在时初始化空列表,避免空指针
      testMap.putIfAbsent('dn', () => []).add('test name1');
      testMap.putIfAbsent('ph', () => []).add('4160000000');
      testMap.putIfAbsent('dn', () => []).add('test name2');
      testMap.putIfAbsent('ph', () => []).add('7780000000');
    }
    
    按这种写法打印testMap得到的结果为:{dn: [test name1, test name2], ph: [4160000000, 7780000000]},可以保留所有写入的值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 06:27:03