【问题标题】:Dart:How to convert simple map into list in dart/flutter?Dart:如何将简单的地图转换为 dart/flutter 中的列表?
【发布时间】:2020-07-03 14:54:09
【问题描述】:

我想将一个简单的地图转换成一个列表,目前我有{Jack: 23, Adam: 27, Katherin: 25} 并想实现[{ Jack, 23 }, { Adam, 27 }, { Katherin, 25 }]

【问题讨论】:

    标签: arrays list dictionary flutter dart


    【解决方案1】:

    在这里你可以找到一个例子,关键 - 使用map.entries

    class Person {
      final String name;
      final int age;
    
      Person(this.name, this.age);
    }
    
    void test() {
      final map = <String, int>{"Jack": 23, "Adam": 27, "Katherin": 25};
    
      final list = map.entries.map((entry) => Person(entry.key, entry.value)).toList();
    }
    

    如果不想使用 Person 类,可以使用带有 tuple 的包 https://pub.dev/packages/tuple

    【讨论】:

    • 但是假设我没有模型,那么要做什么或人员类?
    • 您可以使用提供元组功能的包或创建 Person 类(对我来说更好)检查更新的答案
    • 我可以将地图一张一张地添加到列表中吗?那么这也能解决我的问题吗?
    • 当然,你可以在item是map的地方添加到list items,并且会有List&lt;Map&lt;String, int&gt;&gt; list = map.entries.map((entry) =&gt; &lt;String, int&gt;{entry.key: entry.value}).toList();但是我不推荐这种方式
    猜你喜欢
    • 2013-05-25
    • 2020-05-27
    • 2019-12-05
    • 1970-01-01
    • 1970-01-01
    • 2019-05-30
    • 2021-12-18
    • 2018-12-13
    • 2022-01-08
    相关资源
    最近更新 更多