Flutter Local Storage
tip
note
Implementation Date: Jul/23
Version: 2.2.0
Description Methods
- Load an item;
- Save an item;
- Remove an item;
- Load Many items;
- Save Many items;
Abstract Class
abstract class ILocalStorage {
Future<dynamic> load({required String key});
Future<bool> save({required String key, required value});
Future<bool> remove({required String key});
Future<List<String>?> loadMany({required String infoKey});
Future<bool> saveMany(
{required String infoKey, required List<String> dataList});
}
Implementation Class
class LocalSharedPreferences implements ILocalStorage {
const LocalSharedPreferences();
@override
Future<dynamic> load({required String key}) async {
final sharedPreferences = await SharedPreferences.getInstance();
if (sharedPreferences.containsKey(key)) {
final doc = sharedPreferences.get(key);
return doc;
} else {
return null;
}
}
@override
Future<List<String>?> loadMany({required String infoKey}) async {
final sharedPreferences = await SharedPreferences.getInstance();
List<dynamic>? list = sharedPreferences.getStringList(infoKey);
if (list != null && list is List<String>) {
list = list.cast<String>().toList();
return list.toList();
} else {
return null;
}
}
@override
Future<bool> save({required String key, required value}) async {
final sharedPreferences = await SharedPreferences.getInstance();
if (value is String) {
return sharedPreferences.setString(key, value);
} else if (value is bool) {
return sharedPreferences.setBool(key, value);
} else if (value is int) {
return sharedPreferences.setInt(key, value);
} else if (value is double) {
return sharedPreferences.setDouble(key, value);
} else if (value is List<String>) {
return sharedPreferences.setStringList(key, value);
}
throw Exception('Value type (${value.runtimeType}) not valid');
}
@override
Future<bool> saveMany({required String infoKey, required List<String> dataList}) async {
final sharedPreferences = await SharedPreferences.getInstance();
return sharedPreferences.setStringList(infoKey, dataList);
}
@override
Future<bool> remove({required String key}) async {
try {
final sharedPreferences = await SharedPreferences.getInstance();
sharedPreferences.remove(key);
return true;
} catch (e) {
log(e.toString());
log(StackTrace.current.toString());
return false;
}
}
}
danger
Contributor: BrAcInhO