首页 > 解决方案 > 列表视图使用 Flutter 中的属性过滤掉最后一行数据

问题描述

我有一个包含项目名称、索引和计数的列表。现在有多个具有相同索引的项目,但我想将它们过滤到一个新列表中,每个索引只有最后一行数据。

例如,如果我的列表如下:

ALPHa  index 0 and count is 2
ALPHa  index 0 and count is 3
ALPHa  index 0 and count is 4
ALPHa  index 0 and count is 5
ALPHa  index 0 and count is 4
ALPHa  index 0 and count is 3
ALPHa  index 0 and count is 2
ALPHa  index 0 and count is 1
ALPHa  index 0 and count is 5
ALPHa  index 0 and count is 0
BETA  index 1 and count is 1
BETA  index 1 and count is 2
BETA  index 1 and count is 3
BETA  index 1 and count is 4
BETA  index 1 and count is 3
BETA  index 1 and count is 2
BETA  index 1 and count is 3
BETA  index 1 and count is 4
DELTA  index 2 and count is 4
DELTA  index 2 and count is 1
DELTA  index 2 and count is 2
DELTA  index 2 and count is 3

过滤后的列表应该像

ALPHa  index 0 and count is 0
BETA  index 1 and count is 4
DELTA  index 2 and count is 3

有人可以告诉我如何过滤掉这个吗?

我的代码如下:

模态类:

class CartItems {
  String itemname;
  int numberofitems;
  int index;

  CartItems({
    this.itemname,
    this.numberofitems,
    this.index
  });
}

列表

List <CartItems> cartItems = List();
for(int i =0; i < itemList.length; i++) {
   cartItems.add(CartItems(itemname: itemList[i].itemname, numberofitems: itemList[i].numberofitems,index:index));
}

标签: listflutterdartfilter

解决方案


这是获取过滤列表的一种方法,每个 itemName 中只有最后一个。

List<CartItems> itemList = ...;
var filteredCartItems = new LinkedHashMap<String, CartItems>();
for (CartItems item in itemList ) {
  filteredCartItems[item.itemName] = item;
}

推荐阅读