0

I want to refresh the state of my widget when the following forEach block gets over. But the problem is that before the for loop stops its execution my widget rebuilds it self i.e it doesn't wait for it to execute then refresh.

Code:-

publicQuicksDocuments.forEach((element) async{
  if(element.postIdList.isNotEmpty)
  {
    DocumentSnapshot doc=await postsReference.document(element.id).collection('userPosts').document(element.postIdList.last).get();
    element.postIdList.removeLast();
    postList.add(Post.fromDocument(doc));
  }
  else
  {
    publicPostsDocuments.remove(element);
  }
});           //After this for block overs then below code should execute and refresh the state
postList.shuffle();
setState(() {
  loading=false;
});

Please read the comment in the above code.

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
Deepak Lohmod
  • 2,072
  • 2
  • 8
  • 18

1 Answers1

-1

This should work,

//awaiting for the future to complete.
var variable=await publicQuicksDocuments.forEach((element) async{
  if(element.postIdList.isNotEmpty)
  {
    DocumentSnapshot doc=await postsReference.document(element.id).collection('userPosts').document(element.postIdList.last).get();
    element.postIdList.removeLast();
    postList.add(Post.fromDocument(doc));
  }
  else
  {
    publicPostsDocuments.remove(element);
  }
}); 
//After this for block overs then below code should execute and refresh the state
postList.shuffle();
setState(() {
  loading=false;
});
Madhavam Shahi
  • 1,166
  • 6
  • 17
  • [Never use `Iterable.forEach` with an `async` callback](https://stackoverflow.com/a/63719805/). `Iterable.forEach` does not return anything; you cannot `await` it. – jamesdlin Dec 27 '20 at 07:13