How to use SharedPreferences in flutter
SharedPreferences is a plugin in Flutter that allows us to persistently store and retrieve small amounts of data on the user's device. It is commonly used for storing user preferences, settings, or any data that needs to be accessed quickly and efficiently between app sessions. SharedPreferences provides a simple key-value storage system and is an excellent choice for managing lightweight data.
Adding dependency
To begin using SharedPreferences, we must install the necessary package. For this purpose, we will open the pubspec.yaml in our dart project and add the following line under the "dependencies" section:
dependencies
shared_preferences:
Leaving the version number empty will automatically install the latest version of the package.
After making the changes, we can install the package in two ways:
Right-click the
pubspec.yamlfile and click on "get packages."Write the following command in the terminal:
flutter pub get
We can skip all the above steps and just run the following command, which will automatically install the latest version of shared_preferences package.
flutter pub add shared_preferences
Adding import package statement
Now we can import the package into the Dart file by adding the following line of code in the Dart file where we want to implement the shared_preferences function:
import 'package:shared_preferences/shared_preferences.dart';
Initialize SharedPreferences
The WidgetsFlutterBinding.ensureInitialized() ensures the Flutter engine is properly initialized before proceeding with any other operations. Also, before we can read or write data, we need to initialize the shared_preferences. This is typically done during the app's startup in the main() function or inside the initState() of our main widget.
void main() async {WidgetsFlutterBinding.ensureInitialized();SharedPreferences prefs = await SharedPreferences.getInstance();runApp(MyApp(prefs: prefs));}
Saving data
SharedPreferences support storing int, String, double, and bool data types. We can use the setter methods of the shared_preferences class to save data with a corresponding key. We have defined a function that takes three parameters:
SharedPreferencesinstanceprefs,Unique
keyunder which the value will be stored,The actual
Stringvalue.
// Saving String to Shared Preferencesvoid saveStringData(SharedPreferences prefs, String key, String value) async {prefs.setString(key, value);}// Saving Int to Shared Preferencesvoid saveIntData(SharedPreferences prefs, String key, int value) async {prefs.setInt(key, value);}// Saving Double to Shared Preferencesvoid saveDoubleData(SharedPreferences prefs, String key, double value) async {prefs.setDouble(key, value);}// Saving Bool to Shared Preferencesvoid saveBoolData(SharedPreferences prefs, String key, bool value) async {prefs.setBool(key, value);}
Reading data
To retrieve data from SharedPreferences, use the corresponding getter methods based on the data type we saved. If the value is not present in the storage, it will return null. We can handle this by using the null-aware operator (??) to provide a default value.
// Reading String to Shared PreferencesFuture<String> getStringData(SharedPreferences prefs, String key) async {return prefs.getString(key) ?? "";}// Reading Int to Shared PreferencesFuture<int> getIntData(SharedPreferences prefs, String key) async {return prefs.getInt(key) ?? 0;}// Reading Double to Shared PreferencesFuture<double> getDoubleData(SharedPreferences prefs, String key) async {return prefs.getDouble(key) ?? 0.0;}// Reading Bool to Shared PreferencesFuture<bool> getBoolData(SharedPreferences prefs, String key) async {return prefs.getBool(key) ?? false;}
Removing data
To remove data from SharedPreferences, we can use the remove method and provide the associated key.
// removing data from Shared Preferencesvoid removeData(SharedPreferences prefs, String key) async {prefs.remove(key);}
Checking value existence
To check if a value exists in the SharedPreferences storage, use the containsKey method. It will return true if the given key is present and false otherwise.
// removing data from Shared PreferencesFuture<bool> checkValueExistence(SharedPreferences prefs, String key) async {return prefs.containsKey(key);}
Conclusion
By following these steps, we can effectively use Shared Preferences in your Flutter app to persistently store and retrieve small amounts of data. It's essential for managing user preferences and settings, enhancing the overall user experience, and creating a seamless user journey in your application.
Free Resources