Search code examples
fluttersharedpreferences

Flutter: remove each items saved shared preferences one by one


I am using SharedPreferences and want to delete saved items one by one, but I want to keep some of them. For example, if there are 4 items, then I want to delete just 2 of them. I found how to delete all items at once by using "prefs.clear()" or "prefs.remove('events')".

If you give me any advice, I would appreciate it! Thank you.

  CalendarController _controller;
  Map<DateTime, List<dynamic>> _events;
  List<dynamic> _selectedEvents;
  TextEditingController _eventController;
  SharedPreferences prefs;

  @override
  void initState() {
    super.initState();
    _controller = CalendarController();
    _eventController = TextEditingController();
    _events = {};
    _selectedEvents = [];
    initPrefs();
  }

  initPrefs() async {
    prefs = await SharedPreferences.getInstance();
    setState(() {
      _events = Map<DateTime, List<dynamic>>.from(
          decodeMap(json.decode(prefs.getString("events") ?? "{}")));
    });
  }

  Map<String, dynamic> encodeMap(Map<DateTime, dynamic> map) {
    Map<String, dynamic> newMap = {};
    map.forEach((key, value) {
      newMap[key.toString()] = map[key];
    });
    return newMap;
  }

  Map<DateTime, dynamic> decodeMap(Map<String, dynamic> map) {
    Map<DateTime, dynamic> newMap = {};
    map.forEach((key, value) {
      newMap[DateTime.parse(key)] = map[key];
    });
    return newMap;
  }


  
            ..._selectedEvents.map((event) => ListTile(
                  onLongPress: () {

                   ***// I want to do some action here!!!***

                  }
                  title: Text(event),
                )),
         

Solution

  • I would suggest to get those variables you want to keep, clear shared_preferences and write the variables again. Otherwise you gonna have to remove each variable using preferences.remove('keyName').

    In your code you're saving your events data as a json string. Thus, if I get it right, to remove some variables, you need to get that string, decode json, remove variables, encode the string and save it.

    I would suggest you to make use of sqflite instead of shared_preferences, because it gets more and more complicated to manage your data as your app grows. Shared prefs are used for keeping very simple data between app starts.