如何删除重复列表然后获取最新 ID?

How can I remove duplicate list then get the latest ID?

我有这个 List<Map> :

[
  {msg_id: 1, from_id: 10, to_id: 20, text: 'Some text123'},
  {msg_id: 2, from_id: 20, to_id: 10, text: 'Some text321'},
  {msg_id: 3, from_id: 10, to_id: 20, text: 'Some text again'},
  {msg_id: 4, from_id: 5, to_id: 15, text: 'Hello World'},
  {msg_id: 5, from_id: 15, to_id: 5, text: 'Hello World'}
];

然后我需要通过 msg_id 在不同的聊天室中获取最后一条消息,如下所示:

[
  {msg_id: 3, from_id: 10, to_id: 20, text: 'Some text again'},
  {msg_id: 5, from_id: 15, to_id: 5, text: 'Hello World'}
];

我已经尝试了 distinct()set(),但我仍然感到困惑。我该怎么办?

既然你要的是“group by chat_room_id”,我们需要先从from_id和to_id生成。我假设您的列表已经按 msg_id 排序。我通过在排序后加入 from_id 和 to_id 来生成 chat_room_id。之所以要先排序是因为from_id10,to_id20和from_id20,to_id10.

是同一个聊天室
  List<Map> data = [
    {"msg_id": 1, "from_id": 10, "to_id": 20, "text": 'Some text123'},
    {"msg_id": 2, "from_id": 20, "to_id": 10, "text": 'Some text321'},
    {"msg_id": 3, "from_id": 10, "to_id": 20, "text": 'Some text again'},
    {"msg_id": 4, "from_id": 5, "to_id": 15, "text": 'Hello World'},
    {"msg_id": 5, "from_id": 15, "to_id": 5, "text": 'Hello World'}
  ];
​
  Map<String, Map> perRoom = {};
​
  data.forEach((d) {
    // getting room id
    List<int> roomIdList = [d["from_id"], d["to_id"]];
    // need to be sorted since from_id 10, to_id 20 is the same room as from_id 20, to_id 10
    roomIdList.sort();
    String roomId = roomIdList.join('-');
    perRoom[roomId] = d;
  });
​
  // convert Map<String, Map> back into List<Map>
  List<Map> onlyLatest = perRoom.values.toList();
​
  print(onlyLatest);

on Dartpad

如果您的列表来自查询,我真的建议您在数据库中使用 chat_room_id,因为您可以只使用 GROUP BY 之类的东西,避免从数据库中获取大量数据。