Search code examples
listflutterdartsharedpreferences

delete one element in a list in sharedPreferences


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

Solution

  • 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);