Flutter How Save to List with Shared Preference

857 Views Asked by At

How can I save values to a list with SharedPreferences?

It's a simple list with a date and one value, for example, a list of my weight and sorting the list by date.

1

There are 1 best solutions below

2
On

After searching a lot of articles here you are

For Saving data, must be converted to JSON

 SharedPreferences prefs = await SharedPreferences.getInstance();

   Map<String, dynamic> user = 
    {'weight':[60,70],'height':[70,90]};

bool result = await prefs.setString('user', jsonEncode(user));

For Gettin data, must Deconverted from JSON

String userPref = prefs.getString('user');
     
Map<String,dynamic> userMap = jsonDecode(userPref) as Map<String, dynamic>;

or

final prefs = await SharedPreferences.getInstance();
await prefs.setStringList('items', <String>['Earth', 'Moon', 'Sun']);