Flutter - how to store a list in GetStorage?

Viewed 2289

For each article the user browses, I want to save the ID information. I am using getstorage my code sample is below.

I can not find a true way also, i am looking best way to save id's list.

    final box = GetStorage();
  List<String> myFavoriteList = [];

  saveFav(String id) {
    myFavoriteList.add(id);
    box.write('favoriteArticles', myFavoriteList.cast<String>());
  }

  ifExistInFav(String id) async {
    bool ifExists = false;
    List<String> my = (box.read('favoriteArticles').cast<String>() ?? []);
    ifExists = my.contains(id) ? true : false;
    return ifExists;
  }
1 Answers

First, you need to define your list and convert it to String.

** note that if you use a custom data type ensure you convert your model to String.

then you can use the following to store a List as a String object

final box = GetStorage('AppNameStorage');
/// write a storage key's value
saveListWithGetStorage(String storageKey, List<dynamic> storageValue) async => await box.write(key: storageKey, value: jsonEncode(storageValue));
/// read from storage
readWithGetStorage(String storageKey) => box.read(storageKey);

the saving procee implemention:

saveList(List<dynamic> listNeedToSave) {
    /// getting all saved data
    String oldSavedData = GetStorageServices().readWithGetStorage('saveList');

/// in case there is saved data
if(oldSavedData != null){
  /// create a holder list for the old data
  List<dynamic> oldSavedList = jsonDecode(oldSavedData);
  
  /// append the new list to saved one
  oldSavedList.addAll(listNeedToSave);
  /// save the new collection
  return GetStorageServices().saveListWithGetStorage('saveList', oldSavedList);
} else{
  /// in case of there is no saved data -- add the new list to storage
  return GetStorageServices().saveListWithGetStorage('saveList', listNeedToSave);
}
}


/// read from the storage
readList() => GetStorageServices().readWithGetStorage('saveList');

then the usage:

onTap: () async => debugPrint('\n\n\n read list items ${jsonDecode(await readList())}\n\n\n', wrapWidth: 800),
Related