Skip to content

Instantly share code, notes, and snippets.

@MacDeveloper1
Created September 6, 2023 09:28
Show Gist options
  • Save MacDeveloper1/31e031c63216299a28e83735c5e8c2da to your computer and use it in GitHub Desktop.
Save MacDeveloper1/31e031c63216299a28e83735c5e8c2da to your computer and use it in GitHub Desktop.
WebHydratedStorage
/// {@template web_hydrated_storage}
/// Implementation of [Storage] which uses session storage of web browser
/// to persist and retrieve state changes.
/// {@endtemplate}
class WebHydratedStorage implements Storage {
const WebHydratedStorage()
: assert(kIsWeb, 'WebHydratedStorage is only available on web platform');
/// Returns instance of [WebStorage].
WebStorage get storage => WebStorage.session;
@override
Future<void> clear() async {
storage.clear();
}
@override
Future<void> close() async {
// Nothing to do.
}
@override
Future<void> delete(String key) async {
storage.removeItem(key);
}
@override
dynamic read(String key) {
final encodedValue = storage.getItem(key);
final value = encodedValue.isNotEmpty
? <String, dynamic>{...json.decode(encodedValue)}
: null;
return value;
}
@override
Future<void> write(String key, value) async {
final encodedValue = json.encode(value);
storage.putItem(key, encodedValue);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment