How to store, retrieve and delete any key-value pair through SharedPreferences in flutter?
Through SharedPreferences we can store and retrieve key value pair even after closing the app. The key-value pair stored through SharedPreferences are not deleted after closing the app. We need to delete this manually. Lets see how to store, retrieve and delete a key-value pair through SharedPreferences.
First we have to import shared_preferences package. check below
import 'package:shared_preferences/shared_preferences.dart';
Storing key-value pair through SharedPreferences. Check below
Future<void> saveTestValue( String testValue ) async {
final prefs = await SharedPreferences.getInstance();
await prefs.setString( "test_value", testValue );
}
Retrieve key-value pair through SharedPreferences. Check below
Future<String?> getTestValue() async {
final prefs = await SharedPreferences.getInstance();
final String? testValue = prefs.getString( "test_value" );
return testValue;
}
Deleting key-value pair through SharedPreferences. Check below
Future<void> deleteTestValue() async {
final prefs = await SharedPreferences.getInstance();
prefs.remove( "test_value" );
}