Sub topic 6
Side effects with BlocListener and BlocConsumer
This chapter assumes you know Dart classes, null safety, async/await, Flutter widgets, BuildContext, and the basic Cubit and Bloc APIs. It also assumes a TodosCubit with a TodosState containing a status such as initial, loading, success, or failure.
A widget build should describe what the screen looks like for a given state. It should not perform one-time actions. Showing a SnackBar, opening a dialog, navigating, and sending an analytics event are side effects. BlocListener handles these actions when a state changes.
Listening without rebuilding
BlocListener calls its listener callback when the selected Bloc or Cubit emits a new state. The listener does not build the screen again.
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
class TodosFeedback extends StatelessWidget {
const TodosFeedback({super.key, required this.child});
final Widget child;
@override
Widget build(BuildContext context) {
return 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 ?? 'Could not load todos',
),
),
);
}
if (state.status == TodosStatus.success) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Todos loaded')),
);
}
},
child: child,
);
}
}The listenWhen function is optional. It receives the previous and current states and returns true only when the listener should run. Here, changes to the todo list alone do not show another message.
Do not put this code in build. A build can run many times, so a SnackBar or navigation call could happen repeatedly. Also avoid using a listener to create the normal screen layout. Use BlocBuilder for that.
Combining rendering and effects
BlocConsumer combines BlocBuilder and BlocListener for a widget that needs both behavior. It provides separate buildWhen and listenWhen filters.
class TodosBody extends StatelessWidget {
const TodosBody({super.key});
@override
Widget build(BuildContext context) {
return BlocConsumer<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 ?? 'Try again later'),
),
);
}
},
buildWhen: (previous, current) =>
previous.status != current.status ||
previous.todos != current.todos,
builder: (context, state) {
if (state.status == TodosStatus.loading) {
return const Center(child: CircularProgressIndicator());
}
if (state.todos.isEmpty) {
return const Center(child: Text('No todos yet'));
}
return ListView(
children: [
for (final todo in state.todos) ListTile(title: Text(todo)),
],
);
},
);
}
}Use BlocConsumer when the same small widget genuinely needs both callbacks. Otherwise, separate BlocListener and BlocBuilder components communicate intent more clearly.
| Need | Widget |
|---|---|
| Render state as widgets | `BlocBuilder` |
| Perform a one-time reaction | `BlocListener` |
| Render and react in one location | `BlocConsumer` |
Event flow
Common mistakes
- Showing a dialog from
builder, which can display it repeatedly. - Omitting
listenWhenwhen only some state changes represent an event. - Calling
context.readin a listener for a Cubit that is outside the widget subtree. - Storing transient effects, such as “show this SnackBar,” as permanent screen data without clearing them.
Exercise
Which widget should show a failure SnackBar while a builder renders the successful todo list?
Show answer
Use BlocListener for the SnackBar and BlocBuilder for the list. Use BlocConsumer only when both responsibilities belong in the same widget.