Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

removeAt function is not working inside "For" function Flutter

I just want to check if an item belongs to calendar, if not I want to remove it but it is not working.

Firstly the process of calculation works just fine and I tested if it gets past the "if" function that contains removeAt() function (it works and it prints the "removing $i") but somehow it does not remove the element, the List returns same as beginning. What is the issue?


List<CalendarItem> items(List<CalendarItem> itemsinit,User user){
  print('FS: ${itemsinit.length}');
  if(searchbydate){
   for(int i=0;i<itemsinit.length;i++){

    FetchUser(itemsinit[i].author)..then((res){

      isuserfollowed(user.id,res.id)..then((result){

        if(user.shouldshowuserinfo(res,result) == 'public'){

          FetchPublicUser(res.id)..then((res23){

            if(doesitembelong(res23,itemsinit[i].item) == false){
              print('removing $i');
              itemsinit.removeAt(i);
            };
          });
        };
      });
    });
  }
}
  print('LS: ${itemsinit.length}');
  return itemsinit;
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

FetchUser, isuserfollowed, and FetchPublicUser all appear to return Futures. You are not awaiting these Futures but instead calling .then on them. This is a problem because your items function will return before the callbacks to .then are even run.

Make the function async and convert the .then calls to awaits.

Future<List<CalendarItem>> items(
    List<CalendarItem> itemsinit, User user) async {
  if (searchbydate) {
    for (int i = 0; i < itemsinit.length; i++) {
      final res = await FetchUser(itemsinit[i].author);
      final result = await isuserfollowed(user.id, res.id);
      if (user.shouldshowuserinfo(res, result) == 'public') {
        final res23 = await FetchPublicUser(res.id);
        if (doesitembelong(res23, itemsinit[i].item) == false) {
          print('removing $i');
          itemsinit.removeAt(i);
        }
      }
    }
  }
  return itemsinit;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading