flutterblocstate-managementflutter-bloc

Flutter Bloc : Cannot add new events after calling close


I have a bloc registered in locator (Get_it). I am using the bloc in multiple UI components. But once i trigger the ui update event from some another screen it gives Cannot add new events after calling close

get_it locator

 locator.registerLazySingleton<MyBloc>(() => MyBloc(locator));

UI

BlocProvider(
create: (context) => locator<MyBloc>(),
  child: BlocBuilder<MyBloc, MyBlocState>(
          builder:(_,state)=> Container()
   )
)

The bloc is registered in the locator, so it is available globally. What is the cause of this error?


Solution

  • The issue is because the BlocProvider is expecting to create a bloc, and remove it after the use. As per docs

    In most cases, BlocProvider should be used to create new blocs which will be made available to the rest of the subtree. In this case, since BlocProvider is responsible for creating the bloc, it will automatically handle closing it.

    Since in this usecase , an already existing bloc needs to be used. So use BlocProivider.value

    BlocProvider.value(
    value:locator<MyBloc>(),
      child: BlocBuilder<MyBloc, MyBlocState>(
              builder:(_,state)=> Container()
       )
    )