How can I save data type map by using SharedPreferences
Solution 1
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);
Solution 2
You can only save a string or a string list in shared preferences, not a map directly. But you can use the dart:convert library and jsonEncode() and jsonDecode() methods to convert your map to/from a string and save it that way.
More info: https://flutter.dev/docs/development/data-and-backend/json
Nate Yeum
Updated on December 24, 2022Comments
-
Nate Yeum over 1 year
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); }