Sub topic 16
Persisting state across restarts with HydratedBloc
By default, a Cubit's state lives in memory. When the OS kills your app or the user restarts it, the state goes back to the initial value. hydrated_bloc is a package that saves state to local storage on every change and restores it the next time the Cubit is created. This chapter covers setup, serialization, schema changes, and testing.
This chapter assumes you can write a Cubit with emit, model state with Equatable, and read JSON maps in Dart. Chapter 15's BlocObserver is not required.
What hydration does
"Hydrating" a Bloc means filling it with previously saved state. The package provides HydratedCubit and HydratedBloc, which behave like Cubit and Bloc plus two extra hooks:
toJson(state)turns a state into aMap<String, dynamic>that can be stored.fromJson(json)turns a stored map back into a state.
The base class calls fromJson once, in the constructor, to pick the starting state. It calls toJson after every emit, then writes the result to a storage object.
Setting up storage
Add hydrated_bloc and path_provider to pubspec.yaml. Storage is a single global object, HydratedBloc.storage. You must set it before you create any hydrated Cubit or Bloc. If you don't, the constructor throws a StorageNotFound error.
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:hydrated_bloc/hydrated_bloc.dart';
import 'package:path_provider/path_provider.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
HydratedBloc.storage = await HydratedStorage.build(
storageDirectory: kIsWeb
? HydratedStorageDirectory.web
: HydratedStorageDirectory(
(await getApplicationDocumentsDirectory()).path,
),
);
runApp(const ThemedApp());
}WidgetsFlutterBinding.ensureInitialized() is needed because path_provider uses platform channels before runApp has run. On the web there is no file system, so the package uses browser storage instead.
A first HydratedCubit: theme mode
A theme preference is a good first case. The state is a single enum, and users expect it to survive restarts.
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.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'] as String?;
return ThemeMode.values.asNameMap()[name];
}
@override
Map<String, dynamic>? toJson(ThemeMode state) => {'mode': state.name};
}
class ThemedApp extends StatelessWidget {
const ThemedApp({super.key});
@override
Widget build(BuildContext context) {
return BlocProvider(
create: (_) => ThemeCubit(),
child: BlocBuilder<ThemeCubit, ThemeMode>(
builder: (context, mode) => MaterialApp(
themeMode: mode,
theme: ThemeData.light(),
darkTheme: ThemeData.dark(),
home: Scaffold(
body: Center(
child: SegmentedButton<ThemeMode>(
segments: const [
ButtonSegment(value: ThemeMode.light, label: Text('Light')),
ButtonSegment(value: ThemeMode.dark, label: Text('Dark')),
],
selected: {if (mode != ThemeMode.system) mode},
emptySelectionAllowed: true,
onSelectionChanged: (s) => context
.read<ThemeCubit>()
.select(s.isEmpty ? ThemeMode.system : s.first),
),
),
),
),
),
);
}
}The only change from a plain Cubit is the base class and the two overrides. Widgets, providers and builders stay the same.
The stored value is a map, not a bare string, so you can add fields later without changing the storage format. Storing the enum's name instead of its index keeps the data valid if someone reorders the enum values.
Decide what to persist
Not every part of a state should be saved. Take the TodosState from earlier in this tutorial. A saved loading status would be wrong after a restart, because no request is running anymore. A saved failure would show a stale error. Save the data and derive the status from it.
import 'package:equatable/equatable.dart';
import 'package:hydrated_bloc/hydrated_bloc.dart';
enum TodosStatus { initial, loading, success, failure }
class TodosState extends Equatable {
const TodosState({
this.status = TodosStatus.initial,
this.todos = const [],
});
final TodosStatus status;
final List<String> todos;
TodosState copyWith({TodosStatus? status, List<String>? todos}) {
return TodosState(
status: status ?? this.status,
todos: todos ?? this.todos,
);
}
@override
List<Object?> get props => [status, todos];
}
class PersistedTodosCubit extends HydratedCubit<TodosState> {
PersistedTodosCubit() : super(const TodosState());
void add(String todo) {
emit(state.copyWith(
status: TodosStatus.success,
todos: [...state.todos, todo],
));
}
@override
TodosState? fromJson(Map<String, dynamic> json) {
final raw = json['todos'] as List<dynamic>;
return TodosState(
status: TodosStatus.success,
todos: raw.cast<String>(),
);
}
@override
Map<String, dynamic>? toJson(TodosState state) {
if (state.status == TodosStatus.loading) return null;
return {'todos': state.todos};
}
}Two rules are at work here:
toJsonreturns only the durable data. The status is not written, andfromJsonsets it tosuccess.toJsonreturnsnullfor states you don't want stored. The write is skipped, so the last saved value stays on disk.
Failure modes and schema changes
Stored JSON outlives your code. An app update can change TodosState, and old data will then reach the new fromJson.
- Exceptions in
fromJson. If it throws, for example from a bad cast, the package reports the error throughonErrorand uses the initial state. The app doesn't crash. Do not rely on this as your plan for migrations, though, because the error also reachesBlocObserver.onErrorand any crash reporter you have. - Returning
null. This also falls back to the initial state, and it's the clean way to reject data you don't recognize. - Missing keys.
json['todos'] as List<dynamic>throws if the key is absent. Useas List<dynamic>? ?? const []when a field may be missing. - Versioning. For breaking changes, add a version field to the map and branch on it.
@override
TodosState? fromJson(Map<String, dynamic> json) {
final version = json['version'] as int? ?? 1;
if (version != 2) return null; // discard data from other schemas
final raw = json['todos'] as List<dynamic>? ?? const [];
return TodosState(status: TodosStatus.success, todos: raw.cast<String>());
}
@override
Map<String, dynamic>? toJson(TodosState state) =>
{'version': 2, 'todos': state.todos};Keys, multiple instances and clearing
Each instance saves under a key made from its runtime type plus its id. By default id is an empty string. Two live instances of the same class therefore share one storage entry and overwrite each other. Override id to separate them:
class NoteCubit extends HydratedCubit<String> {
NoteCubit(this.noteId) : super('');
final String noteId;
@override
String get id => noteId;
void edit(String text) => emit(text);
@override
String? fromJson(Map<String, dynamic> json) => json['text'] as String?;
@override
Map<String, dynamic>? toJson(String state) => {'text': state};
}To erase saved state, for example on logout, you have two options:
| Call | Effect |
|---|---|
| `cubit.clear()` | Deletes the stored entry for that one instance. Current in-memory state is unchanged. |
| `HydratedBloc.storage.clear()` | Deletes every stored entry for the whole app. |
Also be aware of this limit. Hydration happens only in the constructor, so changing the stored data while the app runs has no effect until the Cubit is created again.
Testing hydrated Cubits
Tests don't have a real storage directory. Replace HydratedBloc.storage with a mock. This example uses mocktail and bloc_test, and it relies on the default key ThemeCubit (type name plus an empty id).
import 'package:bloc_test/bloc_test.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:hydrated_bloc/hydrated_bloc.dart';
import 'package:mocktail/mocktail.dart';
class MockStorage extends Mock implements Storage {}
void main() {
late Storage storage;
setUp(() {
storage = MockStorage();
when(() => storage.write(any(), any<dynamic>()))
.thenAnswer((_) async {});
HydratedBloc.storage = storage;
});
test('restores the saved mode', () {
when(() => storage.read('ThemeCubit')).thenReturn({'mode': 'dark'});
expect(ThemeCubit().state, ThemeMode.dark);
});
test('falls back to system on unknown data', () {
when(() => storage.read('ThemeCubit')).thenReturn({'mode': 'neon'});
expect(ThemeCubit().state, ThemeMode.system);
});
blocTest<ThemeCubit, ThemeMode>(
'emits dark when selected',
build: ThemeCubit.new,
act: (cubit) => cubit.select(ThemeMode.dark),
expect: () => [ThemeMode.dark],
);
}The first two tests check hydration directly, and the third checks the normal emit behavior.
Exercise
A user reports that after an app update, the todo screen shows an empty list instead of their saved items, and your crash reporter logs a cast error from fromJson. What most likely happened, and what two changes in fromJson and toJson prevent it from recurring?
Show answer
The new version of TodosState changed its stored JSON shape, so old saved data reached a fromJson that cast a missing or differently typed field and threw. The package caught the error and fell back to the initial state, which is why the list is empty. Fix it by writing a version field in toJson, and by having fromJson read it, supply defaults for missing keys (as List<dynamic>? ?? const []), and return null for versions it cannot read.