hydrate method
void
hydrate({
- Storage? storage,
- OnHydrationError onError = defaultOnHydrationError,
inherited
Populates the internal state storage with the latest state.
This should be called when using the HydratedMixin
directly within the constructor body.
class CounterBloc extends Bloc<CounterEvent, int> with HydratedMixin {
CounterBloc() : super(0) {
hydrate();
}
...
}
Optionally, pass a custom onError callback to handle hydration errors:
class CounterBloc extends Bloc<CounterEvent, int> with HydratedMixin {
CounterBloc() : super(0) {
hydrate(
onError: (error, stackTrace) {
// Do something in response to hydration errors.
// Must return a `HydrationErrorBehavior` to specify whether subsequent
// state changes should be persisted.
return HydrationErrorBehavior.retain; // Retain the previous state.
}
);
}
...
}
Implementation
void hydrate({
Storage? storage,
OnHydrationError onError = defaultOnHydrationError,
}) {
__storage = storage ??= HydratedBloc.storage;
try {
final stateJson = __storage.read(storageToken) as Map<dynamic, dynamic>?;
_state = stateJson != null ? _fromJson(stateJson) : super.state;
_errorBehavior = null;
} catch (error, stackTrace) {
this.onError(error, stackTrace);
_state = super.state;
_onErrorCallbackInProgress = true;
_errorBehavior = onError(error, stackTrace);
} finally {
_onErrorCallbackInProgress = false;
}
if (_errorBehavior == HydrationErrorBehavior.retain) return;
try {
final stateJson = _toJson(state);
if (stateJson != null) {
__storage
.write(storageToken, stateJson)
.then((_) {}, onError: this.onError);
}
} catch (error, stackTrace) {
this.onError(error, stackTrace);
if (error is StorageNotFound) rethrow;
}
}