Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter: when should I dispose BLoC?

Tags:

flutter

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.

like image 462
sgon00 Avatar asked Dec 14 '18 03:12

sgon00


People also ask

When should you dispose of flutters?

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.

Should I use BLoC in Flutter?

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.

How do you get rid of blocs in Flutter?

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.

What is the use of BLoC in Flutter?

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.


1 Answers

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.

like image 155
Jordan Davies Avatar answered Sep 20 '22 03:09

Jordan Davies