i'm looking for a solution to save data after a api call like userData, cartitem ecc.. I used sharedPreferences but i can't directly save the json or the Map<String, dynamic> inside it just String or List.
I'd like to store all my data into one place and call single field using varible.field into my app, it is a correct way to build app and it can be done?
CodePudding user response:
Using the SharedPreferences
package: This package allows you to save key-value pairs of data in a persistent storage (usually on the device's local storage). To save a Map<String, dynamic>
or JSON data
, you can first convert it to a string using the jsonEncode()
function and then save it as a string using the setString()
method of the SharedPreferences
object.
Future<void> saveData(Map<String, dynamic> data) async {
final prefs = await SharedPreferences.getInstance();
await prefs.setString('data', json.encode(data));
}
And to get data
Future<Map<String, dynamic>> getData() async {
final prefs = await SharedPreferences.getInstance();
final dataString = prefs.getString('data');
return jsonDecode(dataString);
}
CodePudding user response:
you can create data in sharedpreferences it is suggested to store small key value pair values in sharedpreferences. but if you have large size of data store it in the database like(SQFlite, Hive) which gives you a lot other features(applying filters on data, accessing data on some condition, making relations etc) in accessing the data.