
Why Your Bloc Doesn't Rebuild: State Equality and Immutable States
- كاتب موثّق
- Flutter 3.x
محتويات المقال
debugPrint inside the Cubit shows three items in state.items, so the logic works and the screen just doesn't follow. Nobody touched the widgets, and restarting the app "fixes" it until the second item again.
The common misconception
emit sends a state to the UI. Change the current state, emit it again, and BlocBuilder rebuilds with the new data.
setState works: change a field, call setState, and Flutter rebuilds whatever you changed. It's tempting to read emit as Bloc's version of setState. And the bug above hides well: the first emit really does reach the screen, so the code looks right in a quick manual test.
What actually happens
emit compares before it notifies
emit API docs are short: "emit does nothing if the state being emitted is equal to the current state." The check happens before anything else, so an equal state never reaches the stream, never reaches onChange, and never reaches BlocBuilder. (How BlocBuilder gets new states onto the screen is a separate story, covered in the article on InheritedWidget.) The Bloc FAQ shows it with two identical states emitted back to back: "only one state change will occur (the second emit will be ignored)."
Equal means ==, and by default that's identity
Object.operator == docs: "The default behavior for all Objects is to return true if and only if this object and other are the same object." When you mutate the state and emit it again, you emit the very object that's already the current state. Whatever its class does in ==, an object is equal to itself, so the emit is dropped.
Why the first tap worked
state.items held three.
Equatable compares values, not history
equatable package gives you: two states are equal when their props are equal, element by element. That fixes "new object, same data", but not mutation. If you build a new state around the same List you just changed, the old state and the new one hold the same list, and they compare equal. The FAQ's caution covers this: "Equatable properties should always be copied rather than modified", with List.of or Map.of. It also warns about the other half: "make sure to pass all properties to the props getter." A field missing from props can change all it wants without the state ever looking different.
final isn't immutable
final List<String> is only a fixed reference: the list behind it can still change. Effective Dart warns against "defining custom equality for mutable classes", because equality and hash codes are built from fields that are then free to change. Real means the collections can't be modified either.
Fixing the cart
class CartState extends Equatable { const CartState(this.items); final List<String> items; @override List<Object> get props => [items];}class CartCubit extends Cubit<CartState> { CartCubit() : super(CartState([])); void add(String item) { state.items.add(item); // changes the list the UI already shows emit(state); // same instance, equal to itself: ignored }}class CartState extends Equatable { // An unmodifiable copy: mutating it throws instead of failing silently CartState(List<String> items) : items = List.unmodifiable(items); final List<String> items; @override List<Object> get props => [items];}class CartCubit extends Cubit<CartState> { CartCubit() : super(CartState(const [])); // A new list in a new state, so old and new aren't equal void add(String item) => emit(CartState([...state.items, item]));}BlocBuilder and a BlocObserver counting state changes. After three adds, the wrong Cubit had one change and showed "1 items". The right one had three changes and showed "3 items". Calling state.items.add on the right version threw UnsupportedError: Cannot add to an unmodifiable list, which turns a silent bug into a loud one.
props | ||
==, three refreshes with identical data gave three state changes, so BlocBuilder was asked to rebuild three times for nothing. The FAQ recommends Equatable "if you want to optimize your code to reduce the number of rebuilds", and not "if you want the same state back-to-back to trigger multiple transitions".
How to apply it in your project
Search for in-place changes Look for state.followed by.add(,.remove(,[...] =or a field assignment inside blocs and cubits. Each one is a bug waiting for its second call.Build a new state for every change Use copyWith, spreads andList.ofso every emit carries new objects. Never emitstateitself after changing it.Freeze the collections Make every field finaland copy collections into unmodifiable ones in the constructor.List every field in props When you add a field to a state class, add it to propsin the same commit. A review checklist item is enough.Test with two or more steps Write blocTestcases that emit at least twice, so the first-emit exception can't hide a mutation.
Key takeaways
emitdrops any state equal to the current one, except the very first emit.An object is always equal to itself, so mutating and re-emitting the state can't rebuild the UI. Equatable compares props; a shared, mutated list or a missing field makes different states look equal.finalfixes the reference, not the contents: use unmodifiable collections and new objects.Without value equality every emit rebuilds; choose Equatable on purpose, and test sequences of states.
التعليقات (0)