0PricingLogin
Flutter Mobile Development · Lesson

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_bloc provides HydratedBloc and HydratedCubit
  • path_provider supplies 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

  1. Events, States, and the Cubit-vs-Bloc Decision
  2. Stream Transformers and Event Debouncing in BLoC
  3. Persisting State with HydratedBloc
  4. Testing BLoCs with bloc_test and Mocktail
← Back to Flutter Mobile Development