Sub topic 16
Persisting state across restarts with HydratedBloc
This chapter assumes you know Dart classes, JSON-like maps, Cubit state, and asynchronous initialization. It focuses on persistence, which saves state so an app can restore it after the process stops.
What HydratedBloc adds
A normal Cubit loses its state when the app process ends. HydratedCubit serializes each emitted state and saves it locally. When the Cubit is created again, it reads the saved value and restores it.
HydratedBloc provides the same behavior for an event-driven Bloc.
| Type | Main input | Persistence hooks |
|---|---|---|
| `Cubit` | Method calls | `toJson` and `fromJson` through `HydratedCubit` |
| `Bloc` | Events | `toJson` and `fromJson` through `HydratedBloc` |
Persistence survives a normal app restart. It does not guarantee survival after the user uninstalls the app or clears its data.
Configure storage
Add these packages to pubspec.yaml:
dependencies:
hydrated_bloc: ^10.0.0
path_provider: ^2.1.0Initialize storage before calling runApp. HydratedStorage writes serialized values to the directory supplied during setup.
import 'package:flutter/material.dart';
import 'package:hydrated_bloc/hydrated_bloc.dart';
import 'package:path_provider/path_provider.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
final directory = await getApplicationDocumentsDirectory();
HydratedBloc.storage = await HydratedStorage.build(
storageDirectory: HydratedStorageDirectory(directory.path),
);
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(home: Scaffold());
}
}The storage must be ready before a hydrated object is constructed. Otherwise, restoration can happen too late or fail during startup.
Implement a HydratedCubit
The Cubit below stores a selected theme. toJson converts the state to data that can be encoded. fromJson performs the reverse conversion.
import 'package:flutter/material.dart';
import 'package:hydrated_bloc/hydrated_bloc.dart';
class ThemeCubit extends HydratedCubit<ThemeMode> {
ThemeCubit() : super(ThemeMode.system);
void select(ThemeMode mode) => emit(mode);
@override
ThemeMode? fromJson(Map<String, dynamic> json) {
final name = json['mode'];
if (name is! String) return null;
return ThemeMode.values.firstWhere(
(mode) => mode.name == name,
orElse: () => ThemeMode.system,
);
}
@override
Map<String, dynamic>? toJson(ThemeMode state) {
return {'mode': state.name};
}
}Returning null from fromJson tells HydratedBloc that the saved value cannot be restored. The Cubit then keeps its initial state. This makes schema changes safer than force-casting every saved field.
Keys, privacy, and clearing state
Hydrated storage normally identifies an object from its type. Renaming a Cubit can therefore make old data unreachable. Override storagePrefix when you need a stable key across class renames.
Do not persist passwords, access tokens, private messages, or other sensitive values without a suitable encrypted storage design. Local persistence is convenient, not automatically secure.
Clear saved data when a user signs out or when the data belongs to a previous account:
await HydratedBloc.storage.clear();Use a more targeted strategy when several accounts share the device, so signing out does not accidentally remove unrelated app data.
Exercise
Why should fromJson validate saved fields instead of assuming that every field has the current type?
Show answer
Persisted data may have been written by an older app version, so validation and defaults prevent restoration from crashing.