I need to get user objects in many places, which contain many fields. After login, I want to save/store these user objects. How can we implement this kind of scenario?
I can't store it like this:
SharedPreferences.Editor prefsEditor = myPrefs.edit(); prefsEditor.putString("BusinessUnit", strBusinessUnit);
We can store fields of any Object to shared preference by serializing the object to String.
Shared Preferences allow you to save and retrieve data in the form of key,value pair. In order to use shared preferences, you have to call a method getSharedPreferences() that returns a SharedPreference instance pointing to the file that contains the values of preferences.
If you're not storing an over abundance of data you can use Gson to convert a Java object to a Json string and store the string in your app preferences. Gson has a toJson(obj) method and visa-vis. Getting data out of app preferences and into an object: String json = appSharedPrefs.
SharedPreferences: Save and Read 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.
You can use gson.jar to store class objects into SharedPreferences. You can download this jar from google-gson
Or add the GSON dependency in your Gradle file:
implementation 'com.google.code.gson:gson:2.8.8'
you can find latest version here
Creating a shared preference:
SharedPreferences mPrefs = getPreferences(MODE_PRIVATE);
To save:
MyObject myObject = new MyObject; //set variables of 'myObject', etc. Editor prefsEditor = mPrefs.edit(); Gson gson = new Gson(); String json = gson.toJson(myObject); prefsEditor.putString("MyObject", json); prefsEditor.commit();
To retrieve:
Gson gson = new Gson(); String json = mPrefs.getString("MyObject", ""); MyObject obj = gson.fromJson(json, MyObject.class);
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