The correct way to use BlocProvider
For those who encountered the same problem
Recently I’ve encountered an error that said I cannot call add
to a closed bloc because it’s closed. The issue occurs because I was using getIt with BlocProvider, for example:
BlocProvider(
create: (_) => getIt.get<StoreBloc>(),
child: SomeChild()
)
The thing is, if we’re using it like this and we calls Navigator.of(context).pop()
, it also closes the bloc inside the getIt. To mitigate this issue, we need to use other method that does not close the bloc when we navigate to other screen. That method is BlocProvider.value
. We should change the above’s method to:
BlocProvider.value(
value: getIt.get<StoreBloc>(),
child: SomeChild()
)
To avoid any errors because of navigation, I recommend if you’re using getIt to store your bloc/cubit, to also use this approach.
That’s all, hope this helps!