π© Sophisticated Shared Preferences
Use shared preferences in the simplest way. We will unlock the full potential of shared preferences by creating a simple flow to store/retrieve shared preferences, which will be independent of data type.
Shared preferences are used to store data in local storage. This data is persisted in memory and can be used later. Generally shared preferences are used to store info which are non-critical to app.
π Learn more about shared preferences here: shared_preferences
πΎ Add Shared Preferences Library
Insert the below code in pubspec.yaml
file of your flutter app.
Let's start by creating an Enum
file. This Enum
will be used to store the keys for our shared preferences data.
π Enum For Keys
The Enum
class will store all our preferences keys in one place. This will simplify the process of creating new keys for preferences.
After we have created keys, letβs create getter
and setter
function for the above Enum
class. This will significantly reduce our work for adding preferences.
Note: We will create
PrefRepository
class below, so donβt worry for now, as you will get not found error. Later you can import the class and error will be resolved.
The next step is creating methods to save/retrieve our preferences. For this, we will create a Singleton
class.
βοΈ Implement Shared Preferences
We need to call
PrefRepository
init
method in our appmain
function as below. This is very important as it will initialize our shared preferences object, without initialization we will get error while using shared preferences.
Now we will add our getter
and setter
method for CRUD operations.
We have created getter
and setter
method to store our data. For example, we create fcmToken
setter
method to store String
FCM token and getFcmToken
getter
method to retrieve String
stored FCM token.
You can add more methods according to your needs. It can be any data from string, integer, boolean, double or any other custom object. To store custom object, convert them to string by using JSON
parser.
Below, we have created methods to store/retrieve data of Config
class.
π At Last Use Shared Preferences
We will now use the previously created preferences in our flutter app.
Once we have completed setup of SharedPreferenceEnum
and PrefRepository
classes, then we can use shared preferences using single object in our entire app. ππ»
β Full Code
Thank you, and I hope this article helped you in some way. If you like the post, please support the article by sharing it. Have a nice day!π
I am an mobile enthusiast π±. My expertise is in Flutter and Android development, with more than 5 years of experience in the industry.
I would love to write technical blogs for you. Writing blogs and helping people is what I crave for π .You can contact me at my email(abdulrehman0796@gmail.com) for any collaboration π
π LinkedIn: https://www.linkedin.com/in/abdul-rehman-khilji/