How can I refresh list of elements called using BLoC pattern managed in separate Stateful Widget?

Issue

enter image description here

I’ve a kind of scenario as displayed in this image. Where in a single screen Post information and comments on that posts are being displayed. Also one can add comment by clicking plus icon and add a new comment.

My Screen Structure is as below:

  • PostDetail
    • PostInfoScreen
    • PostCommentListScreen (This is paginated API call implemented with BLoC Pattern)
    • PostAddNewCommentScreen

Now, the trouble that I’m facing is related to refresh this comment listing when a user add a new comment. (i.e. Initially, 10 comments are there and If I’m adding a new comment from PostAddNewCommentScreen and I move back to PostInfoScreen, comment list from PostCommentListScreen should get refreshed to get newly added comment & one count incremented to previous total count)

What I’m facing is, BLoC for fetching comment list is created in PostCommentListScreen with passed Post id to get comment list. While coming back to PostInfoScreen after adding a new comment how can I add Event to PostCommentListScreen BLoC to make a fresh API call to updated list of comments.

Solution

Anyone who is facing same issue like I’ve face, below is the solution.

  • Use MultiBlocProvider at PostDetail screen and create BLoC using BlocProvider for PostCommentListScreen along with BLoC of PostInfoScreen if it’s there. (In my scenario I’ve multiple BLoC to provide).
  • On PostDetail, declare an instance of PostInfoScreenBloc and PostCommentListScreenBloc and attache it to available BLoC provided from above using BlocProvider.of<T>(context).
  • We can use the instance of PostCommentListScreenBloc to add an event to refresh comment list and get the latest data.

Remember this is only for the scenario where we have a Part of a screen (in my case comment list) in separate StatefulWidget having its own BLoC.

Answered By – Purvik Rana

Answer Checked By – Timothy Miller (FlutterFixes Admin)

Leave a Reply

Your email address will not be published.