Skip to content

Instantly share code, notes, and snippets.

@PlugFox
Last active December 21, 2023 11:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save PlugFox/9820fecbf3aebbb11e252226a853b0f8 to your computer and use it in GitHub Desktop.
Save PlugFox/9820fecbf3aebbb11e252226a853b0f8 to your computer and use it in GitHub Desktop.
Lazy local storage, shared preferences
/* ... */
mixin _LocalStorageAPI on _LocalStorageCache {
Future<String?> getString(String key) => _eval<String?>((db) => db.getString(key));
Future<void> setString(String key, String value) => _eval<void>((db) => db.setString(key, value));
}
class LocalStorage with _LocalStorageCache, _LocalStorageAPI {
LocalStorage(Future<SharedPreferences> Function() initialization) : _$initialization = initialization;
@override
final Future<SharedPreferences> Function() _$initialization;
}
mixin _LocalStorageCache {
abstract final Future<SharedPreferences> Function() _$initialization;
late final Future<SharedPreferences> _$db = _$initialization();
Future<T> _eval<T>(T Function(SharedPreferences db) fn) => _$db.then<T>(fn);
}
class LocalStorageSingleton with _LocalStorageCache, _LocalStorageAPI {
LocalStorageSingleton._();
static final LocalStorageSingleton _$instance = LocalStorageSingleton._();
static LocalStorageSingleton get instance => _$instance;
}
mixin _LocalStorageCache {
late final Future<SharedPreferences> _$db = SharedPreferences.getInstance();
Future<T> _eval<T>(T Function(SharedPreferences db) fn) => _$db.then<T>(fn);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment