4

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 3

3

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();
Sign up to request clarification or add additional context in comments.

Comments

0

You can take advantage of properties of Set.

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

Comments

-1

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;
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.