Simplify Data Persistence in Flutter Using Shared Preferences: A Common Utility Class Example

 Managing Local Storage Data in Flutter Apps with Shared Preferences and a Common Utility Class.


It provides a simple key-value storage solution that can be used to store and retrieve primitive data types, such as booleans, integers, doubles, strings, and lists of strings. 

This makes it a useful tool for managing user preferences, caching data, and persisting app state.



Usage: 

Shared Preferences can be used to store and retrieve key-value data in your Flutter app. It is particularly useful for storing small amounts of data that need to persist between app sessions. 

Some examples of data that could be stored using Shared Preferences include user preferences, app settings, and cached data.

..



Step 1: 📦Add the following dependencies

Run the following commands to add the dependencies to your pubspec.yaml file:

  • flutter pub add shared_preferences

..



Step 2: ðŸ“‚ Create a new utility class for Shared Preferences in Flutter:

  • libs -> utils -> shared_preference_utils.dart and add the following code:

Note that all functions in this class are asynchronous, so you need to use the await keyword when calling them.

..

Call the function you need

To use the functions in this SharedPrefUtils class, you can follow these steps: For example,



SAVE

To save a boolean value to SharedPreferences, you can call the saveBool function:


await SharedPrefUtils.saveBool("myBooleanKey", true);



..

RETRIEVE

To retrieve the saved value, you can call the corresponding function:


bool? retrievedValue = await SharedPrefUtils.getBool("myBooleanKey");



..

REMOVE SPECIFIC

To remove a value from SharedPreferences, you can call the removeData function:


await SharedPrefUtils.removeData("myBooleanKey");



..

CLEAR ALL

To clear all data from SharedPreferences, you can call the clearData function:


await SharedPrefUtils.clearData();

..


Output:

..

Comments