Get distinct element from a List<MyList> in Flutter

606 Views Asked by At

Hi and thanks for the support if anyone answers:

I have a List that I get from an mysql query and it returns several elements in my list. I receive something like this in Flutter:

[0]:ListaTotPaises
gravedad:"3"
pais:"Colombia"
total:"1"

[1]:ListaTotPaises
gravedad:"2"
pais:"Colombia"
total:"1"

[2]:ListaTotPaises
gravedad:"2"
pais:"Spain"
total:"2"

I want to get de different "pais" from this List. In this case I want to work with the values "Colombia" and "Spain" and not twice Colombia.

2

There are 2 best solutions below

0
Tirth Patel On BEST ANSWER

You could use map to get all pais then call toSet to remove duplicates and finally call toList.

myList.map((e) => e.pais).toSet().toList();

You could also use map + contains + forEach method to solve this:

final allPais = myList.map((e) => e.pais);
final distinctPais = [];
allPais.forEach((e) {
  if (!distinctPais.contains(e)) {
    distinctPais.add(e);
  }
});
0
diazwijaya On

Another simple solution using retainWhere

final sets = Set(); 
myList.retainWhere((e) => sets.add(e.pais));