Search code examples
fluttersharedpreferencesprovider

How can I save data type map by using SharedPreferences


I want to save Provider data that type is map by using SharedPreferences but I cannot find the way to save type map..

Is there a way to save map at once??

// Provider data

    class SettingDataHandler extends ChangeNotifier {
    
    
      Map<String, dynamic> selectedTimes = {
        "Pomodoro Setting": 15,
        "Rest Time Setting": 5,
        "Long Rest Time Setting": 15,
        "Term of Resting Time Setting": 5
      };
    
      setTime(String typeOfSetting, int changeValue) {
        selectedTimes.update(typeOfSetting, (value) => changeValue);
        notifyListeners();
      }
    }

// this is the code that I used SharedPreferences

  Future<int> _initPref() async {
      prefs = await SharedPreferences.getInstance();
      var timeData = prefs.get('timeData');
      if (timeData != null) {
        settingDataHandler.selectedTimes["Pomodoro Setting"] = timeData;
      }
    
      pomodoroHandler.pomodoroTime = settingDataHandler.selectedTimes["Pomodoro Setting"];
      pomodoroHandler.time = pomodoroHandler.pomodoroTime * 60;
    
      return 0;
    }


     Future<void> _changedTime() async {
        prefs = await SharedPreferences.getInstance();
        int currentPomodoroTime = settingDataHandler.selectedTimes["Pomodoro Setting"];
        print(currentPomodoroTime);
        await prefs.setInt('timeData', currentPomodoroTime);
      }

Solution

  • There is no option to save the map inside shared preference directly.

    You have to convert the map into a string using json.encode() method. When you get the string back you have to decode it using json.decode().

    First of all import 'dart:convert';

    To save the map into shared preferences

    prefs = await SharedPreferences.getInstance();
    Map<String, dynamic> selectedTimes = {
            "Pomodoro Setting": 15,
            "Rest Time Setting": 5,
            "Long Rest Time Setting": 15,
            "Term of Resting Time Setting": 5
          };
    String encodedMap = json.encode(selectedTimes);
    print(encodedMap);
    
    prefs.setString('timeData', encodedMap);
      
    

    To retrieve Map from shared preferences

    String encodedMap = prefs.getString('timeData');
    Map<String,dynamic> decodedMap = json.decode(encodedMap);
    print(decodedMap);