Search code examples
listflutterduplicatesitemsmaplist

Get distinct element from a List<MyList> in Flutter


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.


Solution

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