Sub topic 7
Handling loading, success and failure
Most screens in a real app wait on something: a network call, a database read, a file. While they wait, the screen has to show a spinner. When the work ends, it shows data or an error. This chapter shows how to model those phases in a Cubit and render each one.
This chapter assumes you know Dart async/await and null safety. It also assumes you have read the earlier chapters on immutable state with Equatable and copyWith, on Cubits, and on BlocProvider and BlocBuilder.
The problem with a single value
A common first attempt keeps only the data in state: a List<String>. That cannot answer three questions the UI must answer:
- Has loading started?
- Did it fail, and why?
- Is an empty list "no results" or "not loaded yet"?
You need a state that records where the work stands, as well as the data. A state object with a status field handles this.
Modeling status with an enum
The state class from the earlier chapter carries a status enum, the data, and an optional error message.
import 'package:equatable/equatable.dart';
enum TodosStatus { initial, loading, success, failure }
class TodosState extends Equatable {
const TodosState({
this.status = TodosStatus.initial,
this.todos = const [],
this.errorMessage,
});
final TodosStatus status;
final List<String> todos;
final String? errorMessage;
TodosState copyWith({
TodosStatus? status,
List<String>? todos,
String? errorMessage,
}) {
return TodosState(
status: status ?? this.status,
todos: todos ?? this.todos,
errorMessage: errorMessage ?? this.errorMessage,
);
}
@override
List<Object?> get props => [status, todos, errorMessage];
}The four values mean:
| Status | Meaning | UI usually shows |
|---|---|---|
| `initial` | Nothing has been requested yet | Empty page or a prompt |
| `loading` | A request is in flight | Progress indicator |
| `success` | The request finished | The data |
| `failure` | The request threw | An error message and a retry action |
Because TodosState extends Equatable, two states with the same status, list, and message are equal. Bloc skips an emit when the new state equals the current one. The list is compared by its contents, so a new list with the same items does not trigger a rebuild.
The Cubit method: emit, await, emit
An async Cubit method follows one pattern. It emits loading, awaits the work, and then emits success or failure. The repository comes in through the constructor so the Cubit never builds its own data source.
import 'package:flutter_bloc/flutter_bloc.dart';
abstract class TodosRepository {
Future<List<String>> fetchTodos();
}
class TodosCubit extends Cubit<TodosState> {
TodosCubit(this._repository) : super(const TodosState());
final TodosRepository _repository;
Future<void> load() 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(),
));
}
}
}The diagram shows the possible transitions.
Each transition is a plain emit. Nothing in the Cubit touches a widget.
Using `copyWith` keeps the old data
The loading emit uses state.copyWith(status: ...), not a fresh TodosState. This keeps the previously loaded todos in state while a refresh runs. The UI can then show the old list with a thin progress bar, rather than a blank screen.
If you want the opposite, so that a reload clears the list, pass todos: const [] in the same call.
A gotcha with nullable fields
Look at errorMessage: errorMessage ?? this.errorMessage. When copyWith is called without an errorMessage, the old message is kept. That means after a failure and a successful retry, the success state still carries the old error text.
The simplest fix is to clear it explicitly where it matters. A common approach is to build the success state without copyWith for that field:
emit(TodosState(status: TodosStatus.success, todos: todos));Another approach is to ignore errorMessage in the UI unless status == TodosStatus.failure. Whichever you choose, pick one and apply it consistently. Stale error text is a frequent source of confusing bugs.
Rendering each status
BlocBuilder reads the status and returns a different widget for each case. A switch expression over the enum makes the compiler check that you handled every value.
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
class TodosView extends StatelessWidget {
const TodosView({super.key});
@override
Widget build(BuildContext context) {
return BlocBuilder<TodosCubit, TodosState>(
builder: (context, state) {
return switch (state.status) {
TodosStatus.initial => const SizedBox.shrink(),
TodosStatus.loading when state.todos.isEmpty =>
const Center(child: CircularProgressIndicator()),
TodosStatus.loading || TodosStatus.success => ListView(
children: [
for (final todo in state.todos) ListTile(title: Text(todo)),
],
),
TodosStatus.failure => Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(state.errorMessage ?? 'Something went wrong'),
TextButton(
onPressed: () => context.read<TodosCubit>().load(),
child: const Text('Retry'),
),
],
),
),
};
},
);
}
}Three details matter here:
- The
loadingcase with an empty list shows a spinner. Aloadingwith existing items falls through to the list, which gives the "keep old data while refreshing" behavior. - The retry button uses
context.read, because it calls a method and does not need to rebuild when the state changes. - Dart 3 requires the
switchexpression to be exhaustive. If you add a fifth status later, this code stops compiling until you handle it.
Showing errors as one-time side effects
A failure often needs a transient message such as a SnackBar, in addition to what the page shows. Building a SnackBar inside builder is wrong, because builder can run many times and may run without a Scaffold ready. Use BlocListener, which runs its callback once per state change.
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,
);
}
}listenWhen compares the previous and current state. Here it only lets the listener run when the status changed, so a later state that keeps failure does not show a second SnackBar.
Wiring it together
The repository is provided above the Cubit, and the Cubit reads it from context. Calling load() right after creation, with the cascade operator .., starts the first fetch.
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
class InMemoryTodosRepository implements TodosRepository {
@override
Future<List<String>> fetchTodos() async => ['Write tests', 'Ship feature'];
}
class App extends StatelessWidget {
const App({super.key});
@override
Widget build(BuildContext context) {
return RepositoryProvider<TodosRepository>(
create: (_) => InMemoryTodosRepository(),
child: BlocProvider(
create: (context) =>
TodosCubit(context.read<TodosRepository>())..load(),
child: const MaterialApp(home: Scaffold()),
),
);
}
}This home is an empty Scaffold to keep the example small. In a real app, you would place TodosErrorListener and TodosView there.
Common errors
- Emitting after
close. If a widget is removed whileawaitis pending, the Cubit may be closed when the future completes. Callingemitthen throws aStateError. Guard withif (isClosed) return;before the final emit when the Cubit can be closed mid-request. - Swallowing the stack trace.
catch (e)keeps only the message. For logging, usecatch (e, stackTrace)and calladdError(e, stackTrace), so aBlocObservercan see it. - Showing raw exception text.
e.toString()is useful while learning but can leak technical details to users. In a real app, map exceptions to short user-facing messages in the Cubit or repository. - Overlapping calls. Two quick calls to
load()run two requests, and the slower one can overwrite the newer one. A Cubit has no concurrency control. The Bloc chapters later show event transformers that solve this. - Rebuilding on every state. Without
buildWhen,BlocBuilderrebuilds for each distinct state. That is fine here, but for large screens considerBlocSelectorto limit rebuilds.
Exercise
A user pulls to refresh while a list is already showing. Your load() emits state.copyWith(status: TodosStatus.loading), and the request then fails. Which fields of the failure state keep their old values, and what does the TodosView above show?
Show answer
The todos field keeps the previous list, because copyWith only replaces the fields you pass. The status becomes failure, and errorMessage holds the new error text. The TodosView hits the failure case, so it shows the error message and the Retry button instead of the list. If you wanted to keep the list visible with an error banner, you would render the list in the failure case as well.
Exercise
Why is listenWhen: (previous, current) => previous.status != current.status used on the error listener, and what would happen without it?
Show answer
Without listenWhen, the listener runs for every state change. If another field changed while the status stayed failure, the SnackBar would appear again. With the condition, the listener only runs when the status itself changes, so each failure shows one SnackBar.