flutter_bloc: Rebuild Optimization, Persistence & Debugging
BlocSelector: Fine-Grained Rebuilds
// Rebuilds ONLY when itemCount specifically changes, ignoring
// unrelated changes to the rest of CartState
BlocSelector<CartBloc, CartState, int>(
selector: (state) => state.itemCount,
builder: (context, count) => Text('$count'),
)
// buildWhen/listenWhen: custom condition for whether to react at all
BlocBuilder<CartBloc, CartState>(
buildWhen: (previous, current) => previous.itemCount != current.itemCount,
builder: (context, state) => Text('${state.itemCount}'),
)BlocProvider.value(): Reusing an Existing Instance
// Passes an EXISTING Bloc into a new route -- avoids recreating it
// or accidentally having it auto-disposed while still needed elsewhere
Navigator.push(context, MaterialPageRoute(
builder: (_) => BlocProvider.value(
value: context.read<CartBloc>(),
child: CheckoutScreen(),
),
))Persisting State with HydratedBloc
// Automatically persists state to local storage and restores it
// on app restart -- no manual serialization/storage code needed
class CartCubit extends HydratedCubit<CartState> {
CartCubit() : super(CartState.empty());
@override
CartState? fromJson(Map<String, dynamic> json) => CartState.fromJson(json);
@override
Map<String, dynamic>? toJson(CartState state) => state.toJson();
}Global Debugging with BlocObserver
// Observes events/state changes/errors across EVERY Bloc in the app
class AppBlocObserver extends BlocObserver {
@override
void onChange(BlocBase bloc, Change change) {
print('${bloc.runtimeType} $change');
super.onChange(bloc, change);
}
}
void main() {
Bloc.observer = AppBlocObserver();
runApp(MyApp());
}Constructor Injection for Testability
LoginBloc(this.authRepository) accepting a repository via the constructor lets a unit test pass LoginBloc(MockAuthRepository()) to fully control its behavior -- the same dependency-injection testability benefit seen with mocking libraries elsewhere.
Keep your own version of these notes — editable, searchable, and organised by your stack.
Start free