saveCacheObjectToList static method
Implementation
static Future<bool> saveCacheObjectToList(
String key, CacheObject cacheObject, String keyField,
{bool overwrite = true, bool deleteOnError = true, int? limit}) async {
try {
if (getSharedPreferences().containsKey(key)) {
List<String> values = getSharedPreferences().getStringList(key)!;
List<String> newValues = [];
bool foundInOld = false;
values.forEach((element) {
if (jsonDecode(_reApplyCacheKey(element))[keyField] ==
cacheObject.getData()[keyField]) {
foundInOld = true;
if (overwrite) {
newValues.add(_applyCacheKey(jsonEncode(cacheObject.getData())));
} else {
newValues.add(element);
}
} else {
newValues.add(element);
}
});
if (!foundInOld) {
newValues.add(_applyCacheKey(jsonEncode(cacheObject.getData())));
}
if (limit != null && limit > 0) {
while (newValues.length > limit) {
newValues.removeAt(0);
}
}
await getSharedPreferences().setStringList(key, newValues);
return true;
} else {
if (await getSharedPreferences().setStringList(
key, [_applyCacheKey(jsonEncode(cacheObject.getData()))])) {
return true;
}
}
} catch (e) {
if (deleteOnError) {
print("CacheHandler: Delete Key: " + key);
await removeCacheObject(key);
}
print(e);
}
return false;
}