92 lines
2.0 KiB
Dart
92 lines
2.0 KiB
Dart
import 'package:get/get.dart';
|
|
import 'package:get_storage/get_storage.dart';
|
|
|
|
class GetStorageService extends GetxService {
|
|
final GetStorage _box = GetStorage();
|
|
|
|
// CREATE / UPDATE
|
|
Future<void> save<T>(String key, T value) async {
|
|
await _box.write(key, value);
|
|
}
|
|
|
|
// READ
|
|
T? get<T>(String key) {
|
|
return _box.read<T>(key);
|
|
}
|
|
|
|
// READ mit Defaultwert
|
|
T getOrDefault<T>(String key, T defaultValue) {
|
|
return get<T>(key) ?? defaultValue;
|
|
}
|
|
|
|
// DELETE
|
|
Future<void> delete(String key) async {
|
|
await _box.remove(key);
|
|
}
|
|
|
|
// EXISTS
|
|
bool exists(String key) {
|
|
return _box.hasData(key);
|
|
}
|
|
|
|
// CLEAR ALL
|
|
Future<void> clear() async {
|
|
await _box.erase();
|
|
}
|
|
|
|
// READ LIST
|
|
List<T> getList<T>(String key) {
|
|
final data = _box.read<List<dynamic>>(key);
|
|
return data?.cast<T>() ?? <T>[];
|
|
}
|
|
|
|
// SAVE LIST
|
|
Future<void> saveList<T>(String key, List<T> items) async {
|
|
await _box.write(key, items);
|
|
}
|
|
|
|
// ADD ITEM
|
|
Future<void> addItem<T>(String key, T item) async {
|
|
final items = getList<T>(key);
|
|
items.add(item);
|
|
await saveList<T>(key, items);
|
|
}
|
|
|
|
// UPDATE ITEM
|
|
Future<void> updateItem<T>(String key, int index, T item) async {
|
|
final items = getList<T>(key);
|
|
|
|
if (index < 0 || index >= items.length) {
|
|
throw RangeError.index(index, items);
|
|
}
|
|
|
|
items[index] = item;
|
|
await saveList<T>(key, items);
|
|
}
|
|
|
|
// DELETE ITEM
|
|
Future<void> deleteItem<T>(String key, int index) async {
|
|
final items = getList<T>(key);
|
|
|
|
if (index < 0 || index >= items.length) {
|
|
throw RangeError.index(index, items);
|
|
}
|
|
|
|
items.removeAt(index);
|
|
await saveList<T>(key, items);
|
|
}
|
|
|
|
Future<void> saveModelList(
|
|
String key,
|
|
List<Map<String, dynamic>> items,
|
|
) async {
|
|
await _box.write(key, items);
|
|
}
|
|
|
|
List<Map<String, dynamic>> getModelList(String key) {
|
|
final data = _box.read<List<dynamic>>(key) ?? [];
|
|
|
|
return data.map((item) => Map<String, dynamic>.from(item as Map)).toList();
|
|
}
|
|
}
|