Wallpaper-Genie/lib/common/utils/shared_util.dart
2024-07-12 16:04:47 +08:00

81 lines
1.6 KiB
Dart

import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
class UPCache {
SharedPreferences? _prefs;
static UPCache? _instance;
UPCache.of() {
init();
}
UPCache._pre(SharedPreferences prefs) {
_prefs = prefs;
}
static UPCache getInstance() {
_instance ??= UPCache.of();
return _instance!;
}
void init() async {
_prefs ??= await SharedPreferences.getInstance();
}
static Future<UPCache> preInit() async {
if (_instance == null) {
var prefs = await SharedPreferences.getInstance();
_instance = UPCache._pre(prefs);
}
return _instance!;
}
void setData<T>(String key, T data) {
if (data is String) {
_prefs?.setString(key, data);
} else if (data is double) {
_prefs?.setDouble(key, data);
} else if (data is int) {
_prefs?.setInt(key, data);
} else if (data is bool) {
_prefs?.setBool(key, data);
} else if (data is List<String>) {
_prefs?.setStringList(key, data);
}
}
void setJson(key, value) {
value = jsonEncode(value);
_prefs?.setString(key, value);
}
Map<String, dynamic>? getJson(key) {
String? result = _prefs?.getString(key);
if (result != null) {
return jsonDecode(result);
}
return null;
}
void remove(String key) {
_prefs?.remove(key);
}
T? get<T>(String key) {
var value = _prefs?.get(key);
if (value != null) {
return value as T;
}
return null;
}
List<String> getStringList(String key) {
var value = _prefs?.getStringList(key);
if (value != null) {
return value;
}
return [];
}
}