nc-photos/app/lib/entity/pref/provider/universal_storage.dart

67 lines
1.9 KiB
Dart
Raw Normal View History

2023-07-17 09:35:45 +02:00
import 'dart:convert';
import 'package:nc_photos/entity/pref.dart';
2023-08-28 19:22:29 +02:00
import 'package:np_universal_storage/np_universal_storage.dart';
2023-07-17 09:35:45 +02:00
/// [Pref] backed by [UniversalStorage]
class PrefUniversalStorageProvider extends PrefProvider {
PrefUniversalStorageProvider(this.name);
Future<void> init() async {
2023-08-28 19:22:29 +02:00
final prefStr = await UniversalStorage().getString(name) ?? "{}";
2023-07-17 09:35:45 +02:00
_data
..clear()
..addAll(jsonDecode(prefStr));
}
@override
2023-07-17 10:23:57 +02:00
bool? getBool(PrefKeyInterface key) => _get<bool>(key);
2023-07-17 09:35:45 +02:00
@override
2023-07-17 10:23:57 +02:00
Future<bool> setBool(PrefKeyInterface key, bool value) => _set(key, value);
2023-07-17 09:35:45 +02:00
@override
2023-07-17 10:23:57 +02:00
int? getInt(PrefKeyInterface key) => _get<int>(key);
2023-07-17 09:35:45 +02:00
@override
2023-07-17 10:23:57 +02:00
Future<bool> setInt(PrefKeyInterface key, int value) => _set(key, value);
2023-07-17 09:35:45 +02:00
@override
2023-07-17 10:23:57 +02:00
String? getString(PrefKeyInterface key) => _get<String>(key);
2023-07-17 09:35:45 +02:00
@override
2023-07-17 10:23:57 +02:00
Future<bool> setString(PrefKeyInterface key, String value) =>
_set(key, value);
2023-07-17 09:35:45 +02:00
@override
2023-07-17 10:23:57 +02:00
List<String>? getStringList(PrefKeyInterface key) => _get<List<String>>(key);
2023-07-17 09:35:45 +02:00
@override
2023-07-17 10:23:57 +02:00
Future<bool> setStringList(PrefKeyInterface key, List<String> value) =>
2023-07-17 09:35:45 +02:00
_set(key, value);
@override
2023-07-17 10:23:57 +02:00
Future<bool> remove(PrefKeyInterface key) async {
2023-07-17 09:35:45 +02:00
final newData = Map.of(_data)..remove(key.toStringKey());
2023-08-28 19:22:29 +02:00
await UniversalStorage().putString(name, jsonEncode(newData));
2023-07-17 09:35:45 +02:00
_data.remove(key.toStringKey());
return true;
}
@override
Future<bool> clear() async {
2023-08-28 19:22:29 +02:00
await UniversalStorage().remove(name);
2023-07-17 09:35:45 +02:00
_data.clear();
return true;
}
2023-07-17 10:23:57 +02:00
T? _get<T>(PrefKeyInterface key) => _data[key.toStringKey()];
2023-07-17 09:35:45 +02:00
2023-07-17 10:23:57 +02:00
Future<bool> _set<T>(PrefKeyInterface key, T value) async {
2023-07-17 09:35:45 +02:00
final newData = Map.of(_data)
..addEntries([MapEntry(key.toStringKey(), value)]);
2023-08-28 19:22:29 +02:00
await UniversalStorage().putString(name, jsonEncode(newData));
2023-07-17 09:35:45 +02:00
_data[key.toStringKey()] = value;
return true;
}
final String name;
final _data = <String, dynamic>{};
}