Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete/clear shared-preferences using key in flutter?

I am using the following code which clears all the shared-preferences but I just want to clear/delete particular shared-preferences value using key in a flutter.

For now, I have this which is clearing all the shared-preferences.

 SharedPreferences prefrences = await SharedPreferences.getInstance();
await prefrences.clear();
like image 738
GaganSailor Avatar asked Mar 06 '20 04:03

GaganSailor


People also ask

Where shared preferences are stored in Flutter?

Flutter shared preferences is actually implemented as an in-memory cache. The first time that you call SharedPreferences. getInstance() all the current values are read from NSUserDefaults (on iOS) and SharedPreferences (on Android) and cached in memory.

How do I keep logged in using shared preferences Flutter?

Let start on Project make a flutter project and add dependence and after that, you can clear your main dart file source code. In your main. dart file we create a login page UI and here can entry the user details and on button click store the data in share preferences. so follow full source code on these main.


2 Answers

You can just do this:

prefrences.remove("keyName")

Dart code is pretty easy to read so sometimes when there isn't sufficient documentation, you may just dive into code: https://github.com/flutter/plugins/blob/481e8c251667bcb28d177bfc7d295d584e703bae/packages/shared_preferences/shared_preferences/lib/shared_preferences.dart#L146

like image 100
Manish Avatar answered Sep 29 '22 01:09

Manish


You can delete a particular key if you know in advance which key you want to delete

SharedPreferences sharedPreference = await SharedPreferences.getInstance();
    List<String> keys = sharedPreference.getKeys();
    keys.remove("username");

Hopes that helps

like image 20
Krishna Avatar answered Sep 29 '22 01:09

Krishna