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