How to remove data from the bellow List when the data has same category so gridview has no repeated category name

Viewed 83

I am new to flutter, can someone help me? I need to remove extra from similar categories of List<device>. I will use it in a GridView.builder where a category name is displayed. There can also be no category.

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 need to remove that extra category that has the same category name. I only want one dinning room

2 Answers

you can keep a Set of category you already saw while you are filtering:

class Device {
  final String id;
  final String name;
  final String category;

  Device(this.id, this.name, this.category);
  
  @override
  String toString() => 'Device($id, $name, $category)';
}

void main() {
  final _deviceList = [
    Device('d1', 'Fan', 'LivingRoom'),
    Device('d2', 'Tv', 'LivingRoom'),
    Device('d3', 'Light', ''),
    Device('d4', 'refrigerator', 'Kitchen'),
    Device('d5', 'Big Light', ''),
    Device('d6', 'Oven', 'Kitchen'),
  ];

  final seenCategories = <String>{};

  final filteredDeviceList = _deviceList.where((device) {
    if (seenCategories.contains(device.category)) return false; // <- If you already saw an item from this category, don't keep it
    seenCategories.add(device.category);  // <- We save the catefory in the set to indicates we already saw a divice from this catefory
    return true;
  });
  
  print(filteredDeviceList);
}

It prints:

(Device(d1, Fan, LivingRoom), Device(d3, Light, ), Device(d4, refrigerator, Kitchen))

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

UPDATE! for neglecting repetitive elements follow this:

List<String> temp = [];
List<Device> result= _deviceList.where((element)=>{
if(temp.contains(element.category)){
return false;
} else {
temp.add(element.category);
return true;
}
}).toList();
Related