When to actually close a bloc manually when using the flutter_bloc package?

Issue

I have recently watched felix Angelov’s flutter_bloc package (https://pub.dev/packages/flutter_bloc) speech in youtube (https://www.youtube.com/watch?v=knMvKPKBzGE&t=3s) and it’s amazing!

I have a bit of confusion regarding closing the bloc manually in the dispose method. I heard from the speech that we don’t have to call the dispose method for the blocs if we are using the flutter_bloc package, please correct me if this is wrong.

Thanks in advance

Solution

When you use BlocProvider with a builder, the BlocProvider is taking a responsibility for creating and closing a Bloc. In cases, where you want to provide an existing bloc to a new route, you should use BlocProvider.value instead as it does not automatically close the bloc.

You can refer to documentation

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 the bloc.

In some cases, BlocProvider can be used to provide an existing bloc to a new portion of the widget tree. This will be most commonly used when an existing bloc needs to be made available to a new route. In this case, BlocProvider will not automatically close the bloc since it did not create it.

Answered By – Simon Sot

Answer Checked By – Jay B. (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *