Home > OS >  Remove duplicate item in a list - Flutter
Remove duplicate item in a list - Flutter

Time:11-05

I have a list where users can dynamically add items. The list looks like this :

 [{author: Tsubasa Yamaguchi, created: 24 Juin 2017, total_chapter: 34, genre: seinen, pic: https://www.nautiljon.com/images/more/03/72/278427.jpg, title: Blue Period}, {author: Tsubasa Yamaguchi, created: 24 Juin 2017, total_chapter: 34, genre: seinen, pic: https://www.nautiljon.com/images/more/03/72/278427.jpg, title: Blue Period}]

I don't want any duplicates in this list because I display items in a listView. I've tried the method of list.toSet().toList() but for some reason, I have the same result. I think it's because of the format or my items '{}'.

Any suggestion?

This is how I obtain my list :

FirebaseFirestore firestore = FirebaseFirestore.instance;
List favMangasListTitle = [];
List detailledMangaList = [];
String title = '';
String read_chapter = '';
Future<List> getFavMangas() async {
  var value = await firestore.collection("users/${user.uid}/fav_mangas").get();
  final favMangasGetter = value.docs.map((doc) => doc.data()).toList();
  favMangasListTitle.clear();
  detailledMangaList.clear();
  for (var i in favMangasGetter) {
    title = i['title'];
    read_chapter = i['read_chapter'];
    favMangasListTitle.add(title);
  }

  await Future.forEach(favMangasListTitle, (i) async {
    final mangas =
        await firestore.collection('mangas').where('title', isEqualTo: i).get();
    final receivedMangaDetailled =
        mangas.docs.map((doc) => doc.data()).toList();
    detailledMangaList.addAll(receivedMangaDetailled);
  });

  var test = detailledMangaList.toSet().toList();
  print(test);

  return detailledMangaList;
}

CodePudding user response:

As for the comment, while the title is being prioritized, you can create a set of titles and then create a unique map.

     final data = [...yourData]
     final titles = data.map((e) => e["title"]).toSet();

      final result = [];
      for (final title in titles) {
        final item = data.firstWhere((element) =>
            element["title"] == title); // include `orElse` if needed
        result.add(item);
      }
      print(result.toString());

CodePudding user response:

You can use collection package and try this and the data is your list:

var grouped = groupBy(data, (Map value) => value['title']);

var result = grouped.entries.map((e) => e.value.first).toList();
print("result = $result");

first you grouped your itmes in your list by their title and then in second line we chose the first item in each group and that gives us a list without any duplicate with name.

  • Related