restoreFromJsonMap static method
Restores application state from a JSON map.
This method deserializes the JSON map into a Snapshot and restores state from all registered contributors in deterministic order.
Example:
final json = {'schemaVersion': 1, ...};
await StateSnapshot.restoreFromJsonMap(json);
// Or restore only specific keys:
await StateSnapshot.restoreFromJsonMap(json, keys: ['user_state']);
Requirements:
- Checkpoint must be enabled (see enable)
- At least one state contributor must be registered (see register)
- JSON must be valid and match the snapshot schema
Parameters:
json: A JSON-serializable map containing snapshot datakeys: Optional list of keys to restore. If provided, only the specified state contributors will be restored. Ifnull, all registered contributors that exist in the snapshot will be restored.continueOnError: Iftrue, continue restoring other keys even if one fails. Defaults tofalse. Whentrue, errors are logged but don't stop the restore process.
Returns: A Future that completes when restore is finished.
Throws:
- StateError if checkpoint is not enabled
- StateError if no state contributors are registered
- FormatException if the JSON is invalid or doesn't match the schema
- StateError if any importer function throws an error (unless
continueOnErroristrue)
Deterministic Behavior: State is restored in alphabetical order of keys, ensuring deterministic restore behavior regardless of snapshot creation order.
Execution Context: This method should be called from the main isolate. In Flutter, this is typically the UI thread. The restore operation is blocking and will complete before the Future resolves.
Hooks:
- onBeforeRestore callbacks are invoked before restore starts
- onAfterRestore callbacks are invoked after restore completes successfully
Logging: All restore operations are logged using debugPrint for debugging purposes.
Implementation
static Future<void> restoreFromJsonMap(
Map<String, dynamic> json, {
List<String>? keys,
bool continueOnError = false,
}) async {
ensureEnabled();
// Deserialize snapshot
final snapshot = SnapshotSerializer.instance.fromJson(json);
// Invoke before restore hooks
for (final callback in onBeforeRestore) {
try {
callback();
} catch (e, stackTrace) {
debugPrint(
'[Checkpoint] Error in onBeforeRestore callback: $e\n$stackTrace',
);
// Continue with restore even if a hook fails
}
}
// Perform restore
SnapshotManager.instance.restore(
snapshot,
keys: keys,
continueOnError: continueOnError,
);
// Invoke after restore hooks
for (final callback in onAfterRestore) {
try {
callback();
} catch (e, stackTrace) {
debugPrint(
'[Checkpoint] Error in onAfterRestore callback: $e\n$stackTrace',
);
// Continue even if a hook fails
}
}
}