Sub topic 6
Side effects with BlocListener and BlocConsumer
This chapter assumes you know how to build widgets with BlocProvider and BlocBuilder, and that you can write a Cubit with an immutable Equatable state. It uses the TodosCubit and TodosState from the earlier chapters on async state.
Why build methods must stay free of side effects
Flutter can call a build method at any time: on a parent rebuild, a theme change, a hot reload, or a resize. A BlocBuilder builder runs inside build, so any side effect placed there can run many times for one state change. Showing a SnackBar, pushing a route, or starting a timer from a builder is a bug. You may see two SnackBars, or you may get an exception because the framework is already building.
A side effect is any action that does something outside the widget tree description. It does not just return widgets. Typical examples:
- Showing a SnackBar, dialog, or bottom sheet.
- Navigating to or away from a screen.
- Triggering haptic feedback or playing a sound.
- Calling an analytics service.
BlocListener exists for these. It calls a function once for each state change and does not rebuild anything.
BlocListener
BlocListener<B, S> subscribes to the state stream of the nearest B above it. For every new state, it calls listener(context, state). It then returns its child unchanged.
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
class TodosErrorListener extends StatelessWidget {
const TodosErrorListener({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 ?? 'Something went wrong')),
);
}
},
child: child,
);
}
}Three behaviors matter here:
- The listener runs once per emitted state. A rebuild of the surrounding widget does not call it again.
- The
childis built once and reused. A state change never rebuilds it through the listener. listenWhenreceives the previous and current state and returns a bool. Returnfalseto skip the call. This is the same idea asbuildWhenon a builder.
Choosing a good listenWhen
The listener sees every state, so write the condition that describes the event you care about. In the example above, previous.status != current.status skips emissions that only change todos. Inside the listener, the if narrows it to failures.
A tighter version puts the whole condition in listenWhen:
listenWhen: (previous, current) =>
previous.status != current.status &&
current.status == TodosStatus.failure,This pattern also handles retries. If the user taps retry, the Cubit emits loading and then failure again. The status goes failure, loading, failure. The comparison sees a change each time, so each failure shows one SnackBar.
Compare that with a Cubit that emitted failure twice in a row with the same message. Because TodosState uses Equatable, the second state equals the first. Bloc does not emit it, so the listener is not called. If you need two identical failures to produce two notifications, put a new value in the state between them. The loading state in the async pattern already does this.
BlocConsumer
Many screens need both: rebuild on some changes and run a side effect on others. Nesting a BlocListener around a BlocBuilder works, and BlocConsumer is the shorthand for it. It takes both callbacks and both conditions.
| Widget | Rebuilds UI | Runs side effects | Conditions |
|---|---|---|---|
| `BlocBuilder` | Yes | No | `buildWhen` |
| `BlocListener` | No | Yes | `listenWhen` |
| `BlocConsumer` | Yes | Yes | `buildWhen` and `listenWhen` |
Here is a complete example. A save button disables itself while saving. On success the page closes, and on failure a SnackBar appears.
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
enum SaveStatus { idle, saving, saved, failed }
class SaveCubit extends Cubit<SaveStatus> {
SaveCubit(this._save) : super(SaveStatus.idle);
final Future<void> Function() _save;
Future<void> submit() async {
emit(SaveStatus.saving);
try {
await _save();
if (isClosed) return;
emit(SaveStatus.saved);
} catch (_) {
if (isClosed) return;
emit(SaveStatus.failed);
}
}
}
class SavePage extends StatelessWidget {
const SavePage({super.key});
@override
Widget build(BuildContext context) {
return BlocProvider(
create: (_) => SaveCubit(
() => Future<void>.delayed(const Duration(seconds: 1)),
),
child: const SaveView(),
);
}
}
class SaveView extends StatelessWidget {
const SaveView({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Save')),
body: Center(
child: BlocConsumer<SaveCubit, SaveStatus>(
listener: (context, status) {
if (status == SaveStatus.saved) {
Navigator.of(context).pop(true);
} else if (status == SaveStatus.failed) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Could not save')),
);
}
},
builder: (context, status) {
final saving = status == SaveStatus.saving;
return ElevatedButton(
onPressed: saving ? null : () => context.read<SaveCubit>().submit(),
child: Text(saving ? 'Saving...' : 'Save'),
);
},
),
),
);
}
}Open this page with Navigator.of(context).push(MaterialPageRoute(builder: (_) => const SavePage())). Calling pop on a page that is the root route would leave nothing to show.
The isClosed checks matter. If the user leaves the page while _save() is running, BlocProvider closes the Cubit. Calling emit on a closed Cubit throws a StateError. Checking isClosed after each await avoids that.
How the pieces fit
The two gates are independent. A state can trigger the listener and not the builder, the builder and not the listener, both, or neither. Use that to keep each callback small.
Common errors
- Side effect in a builder. The SnackBar appears twice or the framework throws "setState or markNeedsBuild called during build". Move the effect to
listener. - Expecting a call on the first state. The listener skips the initial state. Read
context.read<B>().stateininitStateor a builder if you need to react to the starting value. - Wrong context. The
contextpassed tolisteneris below theBlocProviderof the listened Cubit.ScaffoldMessenger.of(context)still needs aMaterialAppabove it, which normal apps have. - Listening too broadly. A listener with no
listenWhenruns on every emission, including list updates. The effect then fires more often than intended. Compare the specific fields. - Using a Cubit that is not provided.
BlocListenerlooks up the Cubit withcontext. If it is created in the same widget, as inSavePage, put the listener in a child widget such asSaveView. - Stale error text. The
copyWithshown earlier useserrorMessage ?? this.errorMessage, so a later success keeps the old message in the state. The status check in the listener prevents wrong SnackBars. If a screen showserrorMessagedirectly, clear it on purpose in your state design.
Several listeners at once
When one screen reacts to more than one Cubit, MultiBlocListener takes a listeners list and removes the nesting. Each entry is a BlocListener without a child. The chapter on multiple providers covers it with MultiBlocProvider.
Exercise
A screen shows a SnackBar from a BlocBuilder's builder when state.status is failure. The user rotates the device and sees the SnackBar again, although no new failure happened. Why does this happen, and what is the fix?
Show answer
Rotation rebuilds the widget, so the builder runs again with the same failure state, and the side effect runs again. Builders run on every build, not once per state change. Move the SnackBar call into a BlocListener (or the listener of a BlocConsumer) with listenWhen comparing previous.status and current.status. The listener runs only when a new state is emitted.
Exercise
A Cubit emits failure with the message "Offline". The user taps retry and the Cubit emits failure with "Offline" again, with no loading state in between. The state extends Equatable. Will the listener run for the second failure? What would you change if you want a second SnackBar?
Show answer
No. The two states are equal, so Bloc does not emit the second one and the listener is not called. To get a second notification, emit a different state in between, such as a loading state when the retry starts, or add a field that differs between emissions.