Using Shared Preferences in Flutter
Overview
In this article, we'll look into SharedPreferences and how it's utilized in Android and iOS apps. We'll also introduce the shared_preferences plugin and show you how to use it with Flutter. Following that, we'll learn how to import the shared preferences plugin, walk through how to initialize its instance and go through its methods to see what they all offer.
Introduction
You may wish to store data in your Flutter app so that you may utilize it later. This capability is commonly used to save login credentials to be remembered the next time the user runs the app. You may use SharedPreferences to set your Flutter app to remember data even after the user exits the app. To save modest amounts of data in Flutter projects, SharedPreferences is the best solution. Shared Preference is a method for storing and retrieving tiny quantities of primitive data as key/value pairs to a file on device storage such as String, integer, float, and Boolean that comprise your preferences in an XML file inside the program on the device storage. When a user logs in or out of an Android application, the state of login and logout can be stored in shared preferences so that the user doesn't have to type their password repeatedly. Because this is a small amount of data, there is no need for a database; instead, we can store it in shared preferences and access it quickly.
Why Used SharedPreferences in Flutter?
Consider the above case when in an Android application the user logs in or out. We can store the login-logout state in shared preferences so that the user does not need to write a password again and again. We can save the login state in a bool variable because it is a small amount of data and there is no need for a database, so we can store it in shared_preferences to access it quickly. Shared Preference in Flutter allows you to simply read and write key-value pairs in a handful of lines. Nevertheless, keep in mind that shared preference is not a solution for storing sophisticated relational data. SharedPreference stores data in two ways. The first method is to use activity-based preferences, and the second is to create custom preferences. Users must call the method getPreference() for the activity class to get activity preferences. Users must invoke the function getSharedPreference() in case of custom preferences.
getSharedPreferences(): When several SharedPreference files that you indicate with the first parameter's name need to be detected, this technique is employed. Every context in your app can call this function.
getPreferences(): This approach is only used if the activity requires a single preference file. As it will be the sole preference file for this activity, we won't ask for a name in this approach.
How to Use SharedPreferences in Flutter?
Before we begin, we should note that the Flutter SDK does not support SharedPreferences in Flutter; nevertheless, the shared_preferences plugin may be used to save key-value data on the disc. This plugin is available from pub dev, the official package repository for Dart and Flutter programs. The shared preferences plugin encapsulates platform-specific persistent storage for basic data. Because no guarantee that writes will be persisted to disk after returning, this plugin should not be used to save essential data.
To utilize this plugin, we add shared_preferences as a dependency to our project's pubspec.yaml file. Next, you may implement shared preferences in your application by adhering to the plugin's step-by-step implementation shown below.
Implementation
1. Add the Dependencies
If you wish to utilize certain data on a separate page, for instance, you may use shared preferences to save and retrieve that data locally on the device. To add it, you must first access the pubspec.yaml file and enter the following code:
The library is now accessible.
2. Import
We must import the shared preferences plugin into our file before we can utilize it:
A SharedPreferences class that contains methods for setting data of various primitive kinds in SharedPreferences is exported by the shared preferences plugin. It provides a method called getInstance that is used to build a SharedPreferences object.
A SharedPreferences instance is created by the getInstance() method and returned. The instance of SharedPreferences is stored in the prefs.
3. Save Data
Primitive type data can be added to SharedPreferences. The following primitive types can be added:
- int
- string
- bool
- double
Each primitive type has a setter method that corresponds to it. The key of the key-value combination is a string.
Saving an int value
To the counter table of SharedPreferences, this adds an int, 1, as a counter.
Saving a string value
The string "yes" is added to the counter as a result.
Saving a bool value
This updates the counter with the bool value true.
Saving a double value
The counter now has a double value, or 10.2, as a result.
4. Read Data
We have getter methods for obtaining data just as we have setter methods for basic types. The only thing we need to give when getting data from the storage using SharedPreferences is the key.
Get int data
An int value may be retrieved from the SharedPreferences using the getInt method.
Get bool data
The SharedPreferences method getBool returns a boolean value.
Get double data
A double value is returned by the getDouble method from the SharedPreferences.
Get string data
The SharedPreferences' getString function returns a string result.
Null value
A null value might be returned if the value is not in the storage. This may be handled with:
5. Remove Data
We'll apply the remove method to remove data from the SharedPreferences in Flutter. The data's key is supplied to the .remove function, which deletes the key-value pair data in the SharedPreferences.
In this instance, the SharedPreferences counter is removed.
6. Testing
We must simulate the SharedPreferences object that we supply to the SharedPreferencesUtil class to create tests for it. The SharedPreferences.setMockInitialValues() static methods are used for this. The initial state of the SharedPreferences object used in tests is mocked using this method. It requires a parameter of type Map<String, Object>, where the value corresponds to the real SharedPreferences object saved there and the key is used to identify the stored item.
Storage Location by Platform
Key-value pairs are used by SharedPreferences in Flutter to hold initial data. A String must be used as the key in this procedure. Then there is the key's matching value, which may be one of the following: boolean, float, int, long, or string. The Shared Preferences for an app are kept by the Android platform in a private directory in an xml file. Several Shared Preferences files are possible for apps. To save application choices, you would need to utilize shared preferences.
The app data folder has an xml file where SharedPreferences are kept, i.e.
Check Value If Present or Not?
Before reading or writing, we may check in SharedPreferences to determine if the data is present. We'll employ the containsKey technique to do this. The containsKey method uses the data's key as an argument to determine whether the key is present in SharedPreferences. The method outputs a bool, which can be true or false:
The counter is present in the SharedPreferences in the given case. Because of this, it returns true.
It returns false since _counter is missing.
Conclusion
- SharedPreferences is used to allow the Flutter app to save data even after the user quits the app.
- The Shared Preferences method saves and retrieves small amounts of basic data in the form of key/value pairs to a file on the device storage.
- For storing complicated relational data, shared preference is not an option.
- SharedPreference saves data in two ways: getPreference() for the activity class to get activity preferences and getSharedPreference() for custom preferences.
- SharedPreference provides many ways for saving, retrieving, removing, and testing data and these shared preferences are stored in a private directory in an xml file.