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

如何在Dart的for循环中打印Map的字符串值?

在Dart中遍历Map并获取键值对的方法

方法1:通过遍历键集合取值

你当前的循环已经拿到了Map的所有键,直接用manuMap[item]就能获取对应键的值,修改代码如下:

var manuMap = {3 : "hello", 5 : "greetings", 4 : "good buy"};
for (var item in manuMap.keys) {
    print(item.runtimeType);
    print(item);
    // 获取并打印对应的值
    print(manuMap[item]); 
}

方法2:直接遍历键值对条目(更简洁)

Dart的Map提供了entries属性,每个条目(Entry)同时包含key和value,遍历这个属性可以直接拿到键和值:

var manuMap = {3 : "hello", 5 : "greetings", 4 : "good buy"};
for (var entry in manuMap.entries) {
    print('键: ${entry.key}, 值: ${entry.value}');
}

关于manuMap[0]无法生效的原因

你的Map中不存在键为0的条目,Dart中使用map[key]取值时,如果指定的键不存在,会返回null,所以无法得到有效内容。只有传入Map中已存在的键(3、5、4),才能获取到对应的字符串值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 01:52:05