Created
September 6, 2023 09:28
-
-
Save MacDeveloper1/31e031c63216299a28e83735c5e8c2da to your computer and use it in GitHub Desktop.
WebHydratedStorage
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// {@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