Sub topic 2
Rebuilding the UI with BlocBuilder, buildWhen and BlocSelector
This chapter assumes you know Dart 3 sealed classes, Flutter's StatelessWidget, and the TodosState, TodosStatus, and TodosCubit types from earlier chapters.
Rebuilding with BlocBuilder
BlocBuilder rebuilds its subtree each time the state changes. Use buildWhen to skip rebuilds that do not matter to that widget.
BlocBuilder<TodosCubit, TodosState>(
buildWhen: (previous, current) => previous.todos != current.todos,
builder: (context, state) {
return ListView(
children: [for (final todo in state.todos) Text(todo)],
);
},
)BlocSelector goes one step further. It passes only the selected value to the builder and rebuilds only when that value changes.
BlocSelector<TodosCubit, TodosState, bool>(
selector: (state) => state.status == TodosStatus.loading,
builder: (context, isLoading) {
return isLoading
? const CircularProgressIndicator()
: const SizedBox.shrink();
},
)Side effects with BlocListener
A listener runs an action, such as a SnackBar, without changing the widget tree. Use listenWhen so the action runs only on the transition you care about.
BlocListener<TodosCubit, TodosState>(
listenWhen: (previous, current) => previous.status != current.status,
listener: (context, state) {
if (state.status == TodosStatus.failure) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(state.errorMessage ?? 'Something went wrong')),
);
}
},
child: const TodosList(),
)BlocConsumer combines BlocBuilder and BlocListener in one widget when you need both.
Loading, success and failure
Model asynchronous work with a status field. The Cubit emits loading, then success or failure. The UI reads the status to choose what to show.
From Cubit to Bloc: events and handlers
A Bloc receives events through add and handles each event type with on<Event>.
sealed class TodosEvent {}
final class TodosRequested extends TodosEvent {}
class TodosBloc extends Bloc<TodosEvent, TodosState> {
TodosBloc(this._repository) : super(const TodosState()) {
on<TodosRequested>(_onRequested);
}
final TodosRepository _repository;
Future<void> _onRequested(
TodosRequested event,
Emitter<TodosState> emit,
) async {
emit(state.copyWith(status: TodosStatus.loading));
try {
final todos = await _repository.fetchTodos();
emit(state.copyWith(status: TodosStatus.success, todos: todos));
} catch (e) {
emit(state.copyWith(
status: TodosStatus.failure,
errorMessage: e.toString(),
));
}
}
}Choosing between Cubit and Bloc
| Situation | Use |
|---|---|
| Few actions, each one a direct method call | Cubit |
| Actions need a traceable event history or concurrency control | Bloc |
| Simple form or toggle state | Cubit |
Exercise
In BlocBuilder, why does buildWhen matter when the state changes often?
Show answer
It stops the builder from running when the part of the state this widget uses has not changed, which avoids unnecessary rebuilds.