How to remove duplicate elements from a list using lists in Dart / Flutter?

Viewed 1710

How to remove duplicates from a list with lists in Dart / Flutter?

.toSet().toList() doesn't work.

For Example:

List one = [
     [
        [6, 51],
        [2, 76]
     ],
     [
        [6, 51],
        [2, 76]
     ],
     [
        [5, 66],
        [4, 96]
     ]
]

Would be:

List two = [
     [
        [6, 51],
        [2, 76]
     ],
     [
        [5, 66],
        [4, 96]
     ]
]
3 Answers

I hope this works. Also import 'dart:convert';

List two = 
  one.map((f) => f.toString()).toSet().toList()
  .map((f) => json.decode(f) as List<dynamic>).toList();

You can take advantage of properties of Set.

List two = one.toSet().toList();

Not incredibly efficient, but this could work

void main() {
  List<List<List<int>>> one = [
    [
      [6, 51],
      [2, 76]
    ],
    [
      [6, 51],
      [2, 76]
    ],
    [
      [5, 66],
      [4, 96]
    ]
  ];

  print(one);

  print(one.removeDuplicates());
}

extension ListExtension<T> on List<T> {
  bool _containsElement(T e) {
    for (T element in this) {
      if (element.toString().compareTo(e.toString()) == 0) return true;
    }
    return false;
  }

  List<T> removeDuplicates() {
    List<T> tempList = [];

    this.forEach((element) {
      if (!tempList._containsElement(element)) tempList.add(element);
    });
    
    return tempList;
  }
}

Related