I am working on a Flutter app and using the cubit system in flutter_bloc
for state management. This is my first time using bloc, and I am using the Tutorials on bloclibrary.dev as a guideline. (ex: https://bloclibrary.dev/#/flutterinfinitelisttutorial)
When the state is a user-defined class, the documentation states that you must make sure to emit a new instance of the state in your bloc. In the examples, they do this by copying the entire state and emitting the new copy. Ex. emit(state.copyWith(status: "failure"))
. As I understand it, copyWith is used because the state should extend Equatable
to reduce the number of rebuilds, and therefore the state must be immutable.
I'm having some trouble understanding why the immutable class is used. Intuitively, it seems to me that it would be more memory-intensive to create new instances of the class every time the state changes. I have seen a few examples elsewhere that, instead of using Equatable
, will manually write the overrides for == and hashCode. Then the state would be updating by directly modifying it, ex. emit(state..status = "failure")
. Does creating new instances of the state actually affect memory usage on large-scale applications?
There are pros and cons of using mutable and immutable objects. There are several threads describing the differences on StackOverflow, and also a bunch of articles written on the subject, just a google away. But a few quick answers to the non-immutable-vs-mutable-objects-questions:
No, I wouldn't say that copyWith is used because the state should extend Equatable. I'd flip the conjecture and instead I'd rather say that it is extremely convenient to use copyWith when you just want to alter an object slightly, that is immutable, without creating a new one manually.
Yes creating new instances can be costly. But a word of advice is to stick with the immutable objects (states in this case) as long as possible as it often tend to give safer code and you will get more good feature for free when using e.g. Equatable. Don't start optimizing code before you actually need to. It is hard to know what you mean by large-scale applications... how do you define that, how large is large and does the creation of new immutable objects in your case actually affect the other parts in your "large-scale application" significantly?
I've yet to experience any problem with my states being immutable, and I've used Equatable with flutter_bloc a lot...