Bloc: Right way to dispose the bloc

Created on 15 Feb 2020  路  3Comments  路  Source: felangel/bloc

I believe the widget which creates or uses the bloc should close/dispose it. But when I pass the same bloc down the tree do I have to close it in that particular widget ?
If I do so then the bloc would not be reusable in some other widget which might keep on requiring it after the later widget uses it because it would have already disposed it.
Can you please help me with effectively using bloc without having to close in other child or descendant widget.

flutter_bloc question

All 3 comments

Hi @basnetjiten 馃憢
Thanks for opening an issue!

The recommended approach is to use BlocProvider(create: (context) => MyBloc(), child: MyChild()) to create and provide the bloc at the nearest common ancestor of all widgets which need access to the bloc. You should not be manually closing the bloc because BlocProvider automatically handles closing for you when BlocProvider is removed from the widget tree 馃憤

Hope that helps!

Hi @felangel. what if I don't want to dispose the bloc automatically by the providers? because I want the same bloc to be reusable in another widget as well?
And is it still true both BlocProvider and MultiBlocProvider disposes the bloc automatically ?

In cases where you want multiple widgets to have access to the same bloc you can just provide the bloc at the nearest common ancestor. MultiBlocProvider doesn鈥檛 close by default it just allows you to have multiple providers and it鈥檚 up to the individual BlocProviders to handle closing blocs automatically. Does that help clarify things?

Was this page helpful?
0 / 5 - 0 ratings

Related issues

rsnider19 picture rsnider19  路  3Comments

Reidond picture Reidond  路  3Comments

clicksocial picture clicksocial  路  3Comments

RobPFarley picture RobPFarley  路  3Comments

1AlexFix1 picture 1AlexFix1  路  3Comments