D
State ManagementIntermediate30 XP3 min read

How do you persist BLoC/Cubit state across app restarts?

TL;DR: Use HydratedBloc/HydratedCubit from the hydrated_bloc package. It automatically serializes state to local storage and rehydrates it on the next app launch.

Full Answer

HydratedBloc extends the standard BLoC library with automatic state persistence using a storage backend (default: HydratedStorage backed by hive).

Override fromJson and toJson in your Bloc/Cubit to define serialization. On startup, HydratedBloc calls fromJson with the stored data to restore the last state.

๐ŸŽฏ

Don't persist sensitive data (tokens, passwords) via HydratedBloc โ€” it uses unencrypted local storage. Use flutter_secure_storage for sensitive data.

Code Examples

dartHydratedCubit for theme persistence
Output
On first launch: ThemeMode.system. After setTheme(ThemeMode.dark) + app restart: ThemeMode.dark restored automatically

Common Mistakes

  • โœ—Forgetting HydratedBloc.storage setup in main() โ€” throws uninitialized storage error
  • โœ—Returning null from toJson โ€” clears the persisted state silently

Interview Tip

๐Ÿ’ก

HydratedBloc is a great answer to 'how do you handle offline persistence in BLoC apps?' โ€” shows practical library knowledge.

#HydratedBloc#persistence#SharedPreferences#offline