Sub topic 7
Handling Loading, Success, and Failure
This chapter assumes you know Dart classes, async and await, null safety, Flutter widgets, BuildContext, and basic Bloc or Cubit usage. The goal is to represent every meaningful phase of asynchronous work in state, rather than hiding it inside a widget.
Model the request as state
A request usually has at least three visible phases:
loading: the request is in progress.success: data was received.failure: the request did not complete successfully.
An enum makes these phases explicit. The state also stores the current data and an optional error message.
import 'package:equatable/equatable.dart';
import 'package:flutter_bloc/flutter_bloc.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;
static const Object _missing = Object();
TodosState copyWith({
TodosStatus? status,
List<String>? todos,
Object? errorMessage = _missing,
}) {
return TodosState(
status: status ?? this.status,
todos: todos ?? this.todos,
errorMessage: identical(errorMessage, _missing)
? this.errorMessage
: errorMessage as String?,
);
}
@override
List<Object?> get props => [status, todos, errorMessage];
}
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,
errorMessage: null,
));
try {
final todos = await _repository.fetchTodos();
emit(state.copyWith(
status: TodosStatus.success,
todos: todos,
errorMessage: null,
));
} catch (error) {
emit(state.copyWith(
status: TodosStatus.failure,
errorMessage: error.toString(),
));
}
}
}copyWith returns a new state instead of modifying the existing state. The sentinel object lets the method distinguish between “keep the current error” and “clear the error.” This matters when a successful retry should remove an old error message.
The repository owns data access. The Cubit coordinates the request and converts its result into UI state. The widget does not need to know whether the data came from HTTP, a database, or a test double.
Render each state deliberately
A BlocBuilder can select the right UI for the current phase.
BlocBuilder<TodosCubit, TodosState>(
builder: (context, state) {
if (state.status == TodosStatus.loading && state.todos.isEmpty) {
return const Center(child: CircularProgressIndicator());
}
if (state.status == TodosStatus.failure) {
return Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(state.errorMessage ?? 'Could not load todos'),
ElevatedButton(
onPressed: () => context.read<TodosCubit>().load(),
child: const Text('Retry'),
),
],
),
);
}
return ListView(
children: [
for (final todo in state.todos) ListTile(title: Text(todo)),
],
);
},
)Checking state.todos.isEmpty allows a refresh to keep displaying old data while a loading indicator appears elsewhere. Without that distinction, every refresh replaces useful content with a blank spinner.
Request lifecycle
Common errors include forgetting to emit loading, showing technical exception text directly to users, and starting the Cubit request from build without controlling repeated calls. Start the request from a provider, a lifecycle method, or an explicit user action.
Exercise
Why should a failure state contain an error message instead of emitting an empty list?
Show answer
Because an empty list means the successful result contains no items, while an error means the result is unknown and the user may need to retry.