【问题标题】:How to find matching values in two maps in flutter?如何在颤动的两个地图中找到匹配值?
【发布时间】:2021-03-22 14:46:02
【问题描述】:

我正在尝试在两个不同的地图(游戏 - 浮动项目)中找到匹配的“关卡”。如何找到这些项目并创建一个键为“级别”且值与浮动项目匹配的新地图?示例代码如下。

List <Game> games = [
    {
      "id": "Level 1",
      "level": 1,
    },
    {
      "id": "Level 2",
      "level": 2,
    },
    {
      "id": "Level 3",
      "level": 3,
    },
   ];


List <FloatingItem> floatingItems = [
    {
      "level": "1",
      "position": 0
    },
    {
      "level": "1",
      "position": 5
    },
    {
      "level": "3",
      "position": -5
    },
    {
      "level": "3",
       "position": 0
    },
    {
      "level": "2",
      "position": 5
    },
    {
      "level": "3",
      "position": -5
    },
   ];

【问题讨论】:

  • 一定有更好的方法,但 For 循环可以轻松工作。

标签: flutter dart


【解决方案1】:

假设您有这两个列表。我更改了类型,因为我不知道 GameFloatingItem 类的样子。

final List <Map<String, dynamic>> games = [
    {
      "id": "Level 1",
      "level": 1,
    },
    {
      "id": "Level 2",
      "level": 2,
    },
    {
      "id": "Level 3",
      "level": 3,
    },
];

final List <Map<String, dynamic>> floatingItems = [
    {
      "level": 1,
      "position": 0
    },
    {
      "level": 1,
      "position": 5
    },
    {
      "level": 3,
      "position": -5
    },
    {
      "level": 3,
       "position": 0
    },
    {
      "level": 2,
      "position": 5
    },
    {
      "level": 3,
      "position": -5
    },
];

在这里,我通过遍历所有games 并设置键levelfloatingItems 来创建一个新地图。

final Map<String, dynamic>> newMap = games.map((game) => 
  {
    "level": game['level'],
    "floatingItems": floatingItems.where((item) => item['level'] == game['level']),
 });

输出

(
  {
    level: 1, 
    floatingItems: ({level: 1, position: 0}, {level: 1, position: 5})
  },
  {
    level: 2,
    floatingItems: ({level: 2, position: 5})
  }, 
  {
    level: 3,
    floatingItems: ({level: 3, position: -5}, {level: 3, position: 0},
                    {level: 3, position: -5})
  }
)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-09-08
    • 1970-01-01
    • 2016-03-03
    • 2017-02-17
    • 2018-08-21
    • 1970-01-01
    • 2019-09-02
    • 1970-01-01
    相关资源
    最近更新 更多