如何从键列表与单个值生成Map<String, Map<String, dynamic>>?
从键列表生成统一值Map的解决方法
你想要用一个字符串列表作为键,每个键对应同一个shoeSettings值,生成Map<String, Map<String, dynamic>>,期望的最终结构是:
final sneakerBrand = { "addidas": shoeSettings, "nike": shoeSettings, "new balance": shoeSettings, "le coq sportif": shoeSettings };
但你写的代码没达到预期:
final sneakerBrand = { [ "sneaker", "boot", "others", ] .map((brand) => e: shoeSettings) };
你的代码问题在于:map方法返回的是Iterable对象,不能直接放在Map的初始化大括号里;而且map的回调写法错误,没有把列表中的元素作为键来生成键值对。
下面给你几种可行的正确写法:
方法1:用Map.fromIterable直接生成
这是最简洁的实现方式,利用Dart内置的Map.fromIterable方法,指定键和值的生成规则:
final sneakerBrand = Map.fromIterable( ["addidas", "nike", "new balance", "le coq sportif"], key: (item) => item, // 列表元素作为键 value: (_) => shoeSettings, // 所有键对应同一个值 );
方法2:用fold逐步构建Map
通过遍历列表,逐步向空Map中添加键值对:
final brandList = ["addidas", "nike", "new balance", "le coq sportif"]; final sneakerBrand = brandList.fold<Map<String, Map<String, dynamic>>>( {}, // 初始空Map (currentMap, brand) { currentMap[brand] = shoeSettings; return currentMap; }, ); // 或者用更简洁的级联写法: // final sneakerBrand = brandList.fold({}, (map, brand) => map..[brand] = shoeSettings);
方法3:用Map.fromEntries结合map
先把列表元素转换成MapEntry对象,再生成最终的Map:
final brandList = ["addidas", "nike", "new balance", "le coq sportif"]; final sneakerBrand = Map.fromEntries( brandList.map((brand) => MapEntry(brand, shoeSettings)), );
这三种方法都能生成你需要的Map结构,根据自己的习惯选择即可。
内容的提问来源于stack exchange,提问作者Stéphane de Luca
相关产品推荐
相关产品推荐

