0

I have a set of items. From this i want to delete all duplicate values. i tried this finalList = [...{...users!}]; and this print(users.toSet().toList());. But both are printing all the data in the list. It didn't removing duplicate values. Below is my list

List users = [
    {
      "userEmail":"tintu@gmail.com"
    },
    {
      "userEmail":"john@gmail.com"
    },
    {
      "userEmail":"tintu@gmail.com"
    },
    {
      "userEmail":"rose@gmail.com"
    },
    {
      "userEmail":"john@gmail.com"
    },
  ];

Expected Output

List users = [
    {
      "userEmail":"tintu@gmail.com"
    },
    {
      "userEmail":"john@gmail.com"
    },
    {
      "userEmail":"rose@gmail.com"
    },
  ];

Muk System
  • 15
  • 2

2 Answers2

2

Let's try, here you get the unique list

void main() {
  var users = [
    {"userEmail": "tintu@gmail.com"},
    {"userEmail": "john@gmail.com"},
    {"userEmail": "tintu@gmail.com"},
    {"userEmail": "rose@gmail.com"},
    {"userEmail": "john@gmail.com"},
  ];
  var uniqueList = users.map((o) => o["userEmail"]).toSet();
  print(uniqueList.toList());
}
Jahidul Islam
  • 8,525
  • 3
  • 11
  • 32
2

Your attempts don't work because most objects (including Map) use the default implementation for the == operator, which checks only for object identity. See: How does a set determine that two objects are equal in dart? and How does Dart Set compare items?.

One way to make the List to Set to List approach work is by explicitly specifying how the Set should compare objects:

import 'dart:collection';

void main() {
  var users = [
    {"userEmail": "tintu@gmail.com"},
    {"userEmail": "john@gmail.com"},
    {"userEmail": "tintu@gmail.com"},
    {"userEmail": "rose@gmail.com"},
    {"userEmail": "john@gmail.com"},
  ];

  var finalList = [
    ...LinkedHashSet<Map<String, String>>(
      equals: (user1, user2) => user1['userEmail'] == user2['userEmail'],
      hashCode: (user) => user['userEmail'].hashCode,
    )..addAll(users)
  ];
  finalList.forEach(print);
}
jamesdlin
  • 65,531
  • 13
  • 129
  • 158
  • I'am getting error The method '[]' can't be unconditionally invoked because the receiver can be 'null'.Try making the call conditional (using '?.') or adding a null check to the target ('!'). and when i add null check it giving error The operator '[]' isn't defined for the type 'Object'.Try defining the operator '[]'. Without null safety it works fine. – Muk System Oct 25 '21 at 08:16
  • @MukSystem Oops, fixed. – jamesdlin Oct 25 '21 at 08:49
  • It giving error Unhandled Exception: type 'List' is not a subtype of type 'Iterable>' – Muk System Oct 25 '21 at 09:34
  • @MukSystem That's because your original `List` is a `List`. Fix that (as I did in the code above). – jamesdlin Oct 25 '21 at 09:50