Question

Store data as an object in shared preferences in flutter

I want to store an object in shared preferences which contains some fields in it like name, age, phone number etc. I don't know how to store an object in shared preferences in flutter.

 48  68409  48
1 Jan 1970

Solution

 50

You can Store an object in shared preferences as Below:

SharedPreferences shared_User = await SharedPreferences.getInstance();
Map decode_options = jsonDecode(jsonString);
String user = jsonEncode(User.fromJson(decode_options));
shared_User.setString('user', user);
            
SharedPreferences shared_User = await SharedPreferences.getInstance();
Map userMap = jsonDecode(shared_User.getString('user'));
var user = User.fromJson(userMap);
        
class User {
  final String name;
  final String age;
        
  User({this.name, this.age});
        
  factory User.fromJson(Map<String, dynamic> parsedJson) {
    return new User(
      name: parsedJson['name'] ?? "",
      age: parsedJson['age'] ?? "");
  }
        
  Map<String, dynamic> toJson() {
    return {
      "name": this.name,
      "age": this.age
    };
  }
}
2019-04-24

Solution

 50

After searching a lot of articles here you are

For saving data to SharedPreferences instance, object must be converted to JSON:

 SharedPreferences prefs = await SharedPreferences.getInstance();

 Map<String, dynamic> user = {'Username':'tom','Password':'pass@123'};

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

For getting data from SharedPreferences instance, object must converted from JSON:

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

shared_preferences need to be installed: https://pub.dev/packages/shared_preferences/install

2021-03-08