简体   繁体   English

如何在 Dart 中过滤列表?

[英]How to filter a list in Dart?

can some one help me to filter a List that i need to use for gridview.builder where a category name is passed also device id if no category is given my problem is list has same categorized device so i need to filter similar category so the grid has distinct category有人可以帮我过滤一个我需要用于 gridview.builder 的列表,其中一个类别名称也被传递,如果没有给出类别,我的问题是列表具有相同的分类设备,所以我需要过滤类似的类别,以便网格有不同的类别

List<Device> _deviceList = [
  Device('id':'d1', 'Name':'Fan', 'Category':'LivingRoom'),
  Device('id':'d2', 'Name':'Tv', 'Category':'LivingRoom'),
  Device('id':'d3', 'Name':'Light', 'Category':''),
  Device('id':'d4', 'Name':'refrigerator', 'Category':'Kitchen'),
];
// i need to filter this so only one livingroom and any other similar category should come only once in gridview 

I would suggest you this steps: first define a class for Device:我建议您执行以下步骤:首先为设备定义一个类:

class Device{
  String id;
  String name;
  String category;
  
  Device(this.id, this.name, this.category);
}

then filter the given list as follow:然后过滤给定的列表如下:

List<Device> _deviceList = [
  Device('d1', 'Fan', 'LivingRoom'),
  Device('d2', 'Tv', 'LivingRoom'),
  Device('d3', 'Light', ''),
  Device('d4', 'refrigerator', 'Kitchen'),
];

String selectedCategory = "LivingRoom";
  
  List<Device> temp = _deviceList.where((element)=>element.category==selectedCategory).toList();

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

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