import 'dart:convert'; import 'package:nc_photos/entity/pref.dart'; import 'package:nc_photos/mobile/platform.dart' if (dart.library.html) 'package:nc_photos/web/platform.dart' as platform; import 'package:np_common/type.dart'; /// [Pref] backed by [UniversalStorage] class PrefUniversalStorageProvider extends PrefProvider { PrefUniversalStorageProvider(this.name); Future init() async { final prefStr = await platform.UniversalStorage().getString(name) ?? "{}"; _data ..clear() ..addAll(jsonDecode(prefStr)); } @override bool? getBool(PrefKeyInterface key) => _get(key); @override Future setBool(PrefKeyInterface key, bool value) => _set(key, value); @override int? getInt(PrefKeyInterface key) => _get(key); @override Future setInt(PrefKeyInterface key, int value) => _set(key, value); @override String? getString(PrefKeyInterface key) => _get(key); @override Future setString(PrefKeyInterface key, String value) => _set(key, value); @override List? getStringList(PrefKeyInterface key) => _get>(key); @override Future setStringList(PrefKeyInterface key, List value) => _set(key, value); @override Future remove(PrefKeyInterface key) async { final newData = Map.of(_data)..remove(key.toStringKey()); await platform.UniversalStorage().putString(name, jsonEncode(newData)); _data.remove(key.toStringKey()); return true; } @override Future clear() async { await platform.UniversalStorage().remove(name); _data.clear(); return true; } @override Future toJson() async => Map.of(_data); T? _get(PrefKeyInterface key) => _data[key.toStringKey()]; Future _set(PrefKeyInterface key, T value) async { final newData = Map.of(_data) ..addEntries([MapEntry(key.toStringKey(), value)]); await platform.UniversalStorage().putString(name, jsonEncode(newData)); _data[key.toStringKey()] = value; return true; } final String name; final _data = {}; }