Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store data as an object in shared preferences in flutter

Tags:

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.

like image 494
shalini Avatar asked Dec 26 '18 11:12

shalini


People also ask

Can we store object in SharedPreferences 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.

Can we store objects in SharedPreferences?

We can store fields of any Object to shared preference by serializing the object to String.

How do you save data in preferences Flutter?

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.


1 Answers

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     };   } } 
like image 94
Bhoomika Chauhan Avatar answered Sep 19 '22 22:09

Bhoomika Chauhan