Home > Software design >  delete one element in a list in sharedPreferences
delete one element in a list in sharedPreferences

Time:11-05

I'm trying to delete an element in my favoriteList here but this doesn't seem to be working. I've looked on the web but couldn't find anything related to this. They were all about how to clear sharedPreferences or delete a key.

 Future<void> removeFav(String articleId) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    favoriteList = prefs.getStringList('favoriteList');
    if (favoriteList != null) {
      await prefs.remove('${favoriteList!.where((id) => id == articleId)}'); //I'm guessing id here returns an element of this list..??
      print('unfavorited');
      setState(() {
        isFavorite = false;
      });
    } else {
      print('favoriteList was null');
    }
  }

CodePudding user response:

You need to first remove the item from the list:

SharedPreferences prefs = await SharedPreferences.getInstance();

// get the list, if not found, return empty list.
var favoriteList = prefs.getStringList('favoriteList')?? [];

// remove by articleId
favoriteList.removeWhere((item) => item == articleId);

Then, saved the changed favoriteList back to sharedPreferences:

prefs.setStringList('favoriteList', favoriteList);

CodePudding user response:

You should do these steps to save List of object in SharedPreferences:

  • convert your object to map → toMap() method

  • encode your map to string → encode(...) method

  • save the string to shared preferences

for restoring your object:

  • decode shared preference string to a map → decode(...) method

  • use fromJson() method to get your object

So in this case I think you should restore the list from shared preference and modify list and then save new list in shared preference.

  • Related