flutter: Unhandled Exception: Bad state: Cannot add new events after calling close flutter: Unhandled Exception: Bad state: Cannot add new events after calling close dart dart

flutter: Unhandled Exception: Bad state: Cannot add new events after calling close


Use StreamController.isClosed to check if the controller is closed or not, if not closed add data to it.

if (!_controller.isClosed)   _controller.sink.add(...); // safe to add data as _controller isn't closed yet

From Docs:

Whether the stream controller is closed for adding more events.

The controller becomes closed by calling the close method. New events cannot be added, by calling add or addError, to a closed controller.

If the controller is closed, the "done" event might not have been delivered yet, but it has been scheduled, and it is too late to add more events.


If the error is actually caused by the code you posted, I'd just add a check to ensure no new events are added after dispose() was called.

class ServiceBloc extends MainBloc {  final _repo = new Repo();  final PublishSubject<ServiceModel> _serviceController =      new PublishSubject<ServiceModel>();  Observable<ServiceModel> get allServices => _serviceController.stream;  getAllServices() async {    // do nothing if already disposed    if(_isDisposed) {      return;    }    appIsLoading();    ServiceModel movieItem = await _repo.getAllServices();    _serviceController.sink.add(movieItem);    appIsNotLoading();  }  bool _isDisposed = false;  void dispose() {    _serviceController.close();    _isDisposed = true;  }}ServiceBloc serviceBloc = new ServiceBloc();


besides the provided solution I think you should also drain the stream allServices used in your ServiceBloc with:

@overridevoid dispose() {      ...      allServices?.drain(); }