Persisting State with HydratedBloc
Automatically serialize and restore BLoC state across app restarts with hydrated_bloc.
Why Persist BLoC State?
By default, a Bloc or Cubit loses everything when the app process is killed. Reopening the app re-runs the initial state, so the user's last selections, cart contents, or theme are gone.
hydrated_bloc solves this without you writing manual save/load code. It transparently:
- Serializes each new state to local storage as it is emitted
- Restores the last state automatically when the BLoC is recreated
This is ideal for UI preferences, onboarding flags, and small session data that should survive an app restart.
Setup and Storage Initialization
Add the packages to pubspec.yaml:
hydrated_blocprovidesHydratedBlocandHydratedCubitpath_providersupplies a writable directory on the device
Before your app runs, you must build a storage backend and assign it to HydratedBloc.storage. Because this touches platform channels, wrap it with WidgetsFlutterBinding.ensureInitialized().
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
HydratedBloc.storage = await HydratedStorage.build(
storageDirectory: kIsWeb
? HydratedStorageDirectory.web
: HydratedStorageDirectory(
(await getApplicationDocumentsDirectory()).path,
),
);
runApp(const MyApp());
}All lessons in this course
- Events, States, and the Cubit-vs-Bloc Decision
- Stream Transformers and Event Debouncing in BLoC
- Persisting State with HydratedBloc
- Testing BLoCs with bloc_test and Mocktail