Search code examples
listdart

How can I delete duplicates in a Dart List? list.distinct()?


How do I delete duplicates from a list without fooling around with a set? Is there something like list.distinct()? or list.unique()?

void main() {
  print("Hello, World!");

  List<String> list = ['abc',"abc",'def'];
  list.forEach((f) => print("this is list $f"));

  Set<String> set = new Set<String>.from(list);
  print("this is #0 ${list[0]}");
  set.forEach((f) => print("set: $f"));

  List<String> l2= new List<String>.from(set);
  l2.forEach((f) => print("This is new $f"));
}
Hello, World!
this is list abc
this is list abc
this is list def
this is #0 abc
set: abc
set: def
This is new abc
This is new def

Set seems to be way faster!! But it loses the order of the items :/


Solution

  • I have a library called Reactive-Dart that contains many composable operators for terminating and non-terminating sequences. For your scenario it would look something like this:

    final newList = [];
    Observable
       .fromList(['abc', 'abc', 'def'])
       .distinct()
       .observe((next) => newList.add(next), () => print(newList));
    

    Yielding:

    [abc, def]
    

    I should add that there are other libraries out there with similar features. Check around on GitHub and I'm sure you'll find something suitable.