How can you properly store a genuinely more complex object, such as a List of strings or a Map, using SharedPreferences, given that it only genuinely natively supports fairly simple basic primitive types directly?
Short answer
While SharedPreferences directly supports storing a List of strings natively through its own dedicated setStringList method, storing a genuinely more complex arbitrary object, such as a Map or your own genuinely fully custom Dart model class, typically requires first properly…
Advertisement
AModel answer
While SharedPreferences directly supports storing a List of strings natively through its own dedicated setStringList method, storing a genuinely more complex arbitrary object, such as a Map or your own genuinely fully custom Dart model class, typically requires first properly converting that particular object into a JSON formatted string using jsonEncode, storing that resulting string using the regular setString method, and then properly reversing that exact same process using jsonDecode when you later genuinely need to actually read that same particular stored value back again.
final userMap = {'name': 'Alex', 'age': 30};
await prefs.setString('userData', jsonEncode(userMap));
final decoded = jsonDecode(prefs.getString('userData')!);Real-world example
A settings screen stores a user's own several separate notification preferences together as one single combined Map by first properly converting it into a JSON string, correctly retrieving and properly decoding that exact same stored combined preferences object again later using jsonDecode.
Likely follow-ups
- At what specific point does storing genuinely increasingly complex JSON encoded data within SharedPreferences actually genuinely start to become a strong good sign you should instead be using a proper real database like Hive?
- What genuinely happens to overall performance as you continue storing an increasing number of separate individual keys within SharedPreferences?
Related topics