38 lines
814 B
Dart
Executable File
38 lines
814 B
Dart
Executable File
import 'dart:convert';
|
|
|
|
import 'package:shared_preferences/shared_preferences.dart';
|
|
|
|
class SharedPrefsWrapper<T> {
|
|
const SharedPrefsWrapper({
|
|
required this.key,
|
|
required this.fromJson,
|
|
});
|
|
|
|
static SharedPreferences? _sp;
|
|
final String key;
|
|
final T Function(dynamic json) fromJson;
|
|
|
|
Future<void> set(
|
|
T e, [
|
|
List<String> tags = const [],
|
|
]) async {
|
|
_sp ??= await SharedPreferences.getInstance();
|
|
await _sp!.setString(
|
|
key + tags.join('.'),
|
|
jsonEncode(e),
|
|
);
|
|
}
|
|
|
|
Future<T?> get([
|
|
List<String> filter = const [],
|
|
]) async {
|
|
_sp ??= await SharedPreferences.getInstance();
|
|
final source = _sp!.getString(
|
|
key + filter.join('.'),
|
|
);
|
|
if (source == null) return null;
|
|
final json = jsonDecode(source);
|
|
return fromJson(json);
|
|
}
|
|
}
|