繁体   English   中英

列表视图使用 Flutter 中的属性过滤掉最后一行数据

[英]List view filter out last row data using property in Flutter

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

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

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));
}

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

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

试试这个代码 将您的原始列表作为参数传递给将返回过滤后的CartItems List 的方法

List<CartItems> filterList(List<CartItems> itemList){
    int currentItemsIndex = 0;
    CartItems cartItem;
    List < CartItems > cartItems = List();
    for(int i =0 ;i< itemList.length; i++) {
      cartItem = CartItems(itemname: itemList[i].itemname, numberofitems: itemList[i].numberofitems,index:itemList[i].index);
      if(currentItemsIndex == itemList[i].index){
        if(i == itemList.length-1){
          cartItems.add(cartItem);
        }
      }else{
        cartItems.add(cartItem);
      }
      currentItemsIndex = itemList[i].index;

    }
    return cartItems;
  }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM