【问题标题】:Converting Map<key, value> to List<value>将 Map<key, value> 转换为 List<value>
【发布时间】:2019-08-08 06:29:41
【问题描述】:

我一直在寻找一段时间没有成功。我正在尝试将 Map 转换为 List(丢弃密钥)。

当然可以

var addictionList = new List<AddictionDay>();
dataMan.forEach((String date, AddictionDay day) {
    addictionList.add(day);
});

但是有没有更直接的方法,比如

var addictionList = dataMan.toList(); 

?

map 的 Map 函数似乎没有多大帮助,因为它只接受 MapEntry&lt;K2, V2&gt; 作为参数,所以这是不行的。很惊讶以前没有人问过这个问题。

我也在考虑扩展 Map 的新类,但现在我只是在寻找一些本地方法来做到这一点,如果它存在的话。

【问题讨论】:

    标签: list dictionary dart flutter type-conversion


    【解决方案1】:

    Map 类具有entries 属性,该属性将地图条目作为可迭代对象返回,您可以在该可迭代对象上使用map 函数来生成您需要的项目列表。

    var addictionList = dataMan.entries.map((MapEntry mapEntry) => mapEntry.value).toList();
    

    mapEntry.keyString 的类型,mapEntry.valueAddictionDay 的类型。

    【讨论】:

    • .map 返回未定义 .toList 的 Map
    • 而 .map 期望 MapEntry 作为参数。我错过了什么?
    • 错误:返回类型“AddictionDay”不是匿名闭包定义的“MapEntry”。错误:没有为类“地图”定义方法“toList”。
    • 您应该包含显示“dataMan”声明的代码。
    • 我让它与 List&lt;AddictionDay&gt; addictionList = List&lt;AddictionDay&gt;.from(dataMan.entries.map((MapEntry mapEntry) =&gt; mapEntry.value).toList()); 一起工作,因为它返回 List 我无法明确地重铸为 List
    【解决方案2】:

    你需要这个还是更复杂的东西?

      var _map = {1: 'one', 2: 'two', 3: 'three'};
      var values =_map.values.toList();
      print(values);
    

    结果:

    [one, two, three]

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-22
      • 1970-01-01
      • 1970-01-01
      • 2021-12-16
      • 1970-01-01
      • 1970-01-01
      • 2021-03-17
      • 1970-01-01
      相关资源
      最近更新 更多