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.
First, in order to use the SharedPreferences , we have to use Flutter's plugin for it. To do so, make sure dependencies in your pubspec. yaml file looks similar to this: To save something in SharedPreferences , we must provide a value that we want to save and a key that identifies it.
We can store fields of any Object to shared preference by serializing the object to String.
How To Save Data In SharedPreferences In flutter ? To save data in sharedpreferences in flutter declare an object of SharedPreferences class. Initialize the object and call the setter methods to save data. Using sharedpreferences we can save five types of values int, string, double, bool, and stringList.
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 }; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With