Removing non unique Objects from a List (identifiable by a property)

Yon*_*kee 8 list object stream dart flutter

I am capturing events from a stream, each event is a Device Object. The way the stream work is that it is on a timer, so it picks up the same device multiple times and adds to the stream.

I am putting all theres is a List<Device> and putting that into another stream.

I have create a StreamTransformer in the attempt to remove duplicate from the list and then add the unique list back into the stream.

This transform code below, I have tried to add to set and back to list, but this hasn't worked I assume due to the fact they are objects not strings.

  //Transform Stream List by removing duplicate objects
  final deviceList = StreamTransformer<List<Device>, List<Device>>.fromHandlers(
      handleData: (list, sink) {
      List<Device> distinctList = list.toSet().toList();
      sink.add(distinctList);
  });
Run Code Online (Sandbox Code Playgroud)

I have attempted to use .where and other libraries but to no avail and am hoping for some guidance.

Device Object contains unique id and name that could be used to filter out duplicates

Question: How can I remove duplicate objects from a List in Dart?

Thanks in advance.

Osw*_*ann 14

First of all you would need to define by which criteria the objects are supposed to be unique. Is there an identifying property for example? If that is the case the following options should work.

最有效的方法可能是使方法与集合一起工作。为此,您需要将对象转换为数据对象,这意味着让它们通过属性值来识别相等性。为此,您将覆盖相等运算符和哈希码方法。然而,这会改变您的对象在每个相等操作上的行为方式。所以你必须判断这是否合适。请参阅这篇文章

另一种选择是使用地图手动过滤:

class MyObj {
  String val;

  MyObj(this.val);
}

TestListFiltering(){
  List<MyObj> l = [
    MyObj("a"),
    MyObj("a"),  
    MyObj("b"),
  ];
  // filter list l for duplicate values of MyObj.val property
  Map<String, MyObj> mp = {};
  for (var item in l) {
    mp[item.val] = item;
  }
  var filteredList = mp.values.toList();
}
Run Code Online (Sandbox Code Playgroud)