felangel / bloc

A predictable state management library that helps implement the BLoC design pattern
https://bloclibrary.dev
MIT License
11.77k stars 3.39k forks source link

Bad state: Cannot emit new states after calling close #4112

Closed rohit-suthar closed 6 months ago

rohit-suthar commented 6 months ago

Description In our project, we are encountering numerous Firebase crashes associated with this error: "Bad state: Cannot emit new states after calling close."

A very common scenario for reproducing this issue is when a user presses the back button on the screen, and we have initiated an API call on that screen. We emit a new state upon the success of the API, but as the user already navigated back and the bloc is disposed, this error occures.

fernan542 commented 6 months ago

Possible fix:

  1. Move the bloc in the higher part of the widget tree.
  2. Use Stream instead of Future because it is cancellable.
  3. Add a status prop in your State and check if the current state is loading to prevent the user to quickly navigate away from the current screen.
tenhobi commented 6 months ago

You can check whether bloc is closed using isClosed. A lot of people wrap this check and emit within a safeEmit function like this https://github.com/felangel/bloc/issues/3069#issuecomment-1095547362