Home > OS >  ConcurrentModificationError when adding item to a list
ConcurrentModificationError when adding item to a list

Time:11-04

First, here's my code :

FirebaseFirestore firestore = FirebaseFirestore.instance;
List favMangasListTitle = [];
List detailledMangaList = [];
String title = '1';
String read_chapter = '1';
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);
  }

  for (var i in favMangasListTitle) {
    final mangas = await FirebaseFirestore.instance
        .collection('mangas')
        .where('title', isEqualTo: i)
        .get();

    final receivedMangaDetailled =
        mangas.docs.map((doc) => doc.data()).toList();
    detailledMangaList.addAll(receivedMangaDetailled);
  }
  print(detailledMangaList);
  return detailledMangaList;
}

I have a button where I add some mangas to my favorites : Screenshot

When I add one or most mangas, I have this error (line 17)

ConcurrentModificationError (Concurrent modification during iteration: Instance(length:7) of '_GrowableList'.)

It seems to be from my second for loop. But I can't resolve it for 5 days ! Sometimes it's work and sometimes not.

CodePudding user response:

Try to replace your second for loop with this:

await Future.forEach(favMangasListTitle, (element) async {... });
  • Related