When should I dispose BLoC?
Even in the official bloc example code, it creates dispose
methods for the BLoC class, but they never gets called.
Thanks a lot.
Flutter – dispose() Method with Example Dispose is a method triggered whenever the created object from the stateful widget is removed permanently from the widget tree. It is generally overridden and called only when the state object is destroyed.
Bloc is a good pattern that will be suitable for almost all types of apps. It helps improve the code's quality and makes handling states in the app much more manageable. It might be challenging for someone who is just beginning to use Flutter because it uses advanced techniques like Stream and Reactive Programming.
Every BLoC must have a dispose() method This is pretty straight forward. Every BLoC you create should have a dispose() method. This is the place where you do the cleanup or close all the streams you have created. A simple example of the dispose() method is shown below.
BLoC not only solves the code sharing problem but also leverages Streams functionality in order to manage and propagate state changes in Flutter. BLoC helps us to separate Business Logic from UI. In other words, UI components should only worry about the UI and not the logic.
In the specific example you've referenced, the BLoC wouldn't need to be disposed of manually because it needs to be accessible throughout the lifetime of the app so will get disposed of when the app gets disposed. There is a comment to this effect in CartProvider.dart.
If your BLoC is only used by a portion of your app then you should definitely be disposing it. For the example you posted you would probably want to wrap the CartProvider
inside a StatefulWidget
and then dispose of it within the dispose method of that StatefulWidget
's State
object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With