Flutter Categories

Simplifying Data Persistence in Flutter with Shared Preferences

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.


dependencies:
flutter:
sdk: flutter
shared_preferences: ^2.2.2


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.

..

Call the function you need : 

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

For example, 


#1

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


bool valueToSave = true;
String key = "myBooleanKey";

SharedPrefUtils.saveBool(key, valueToSave);



#2

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


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



#3

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


await SharedPrefUtils.removeData("
myBooleanKey");


 

#4

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


await SharedPrefUtils.clearData();



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

..

Code:







..

Output:

..

Comments