Ad

Delete One Element In A List In SharedPreferences

- 1 answer

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');
    }
  }
Ad

Answer

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);
Ad
source: stackoverflow.com
Ad