57

I want to delete all saved shared preferences when the user taps on logout. Are there any ways to do this in a single shot without deleting one by one?

Kaushik Chandru
  • 15,510
  • 2
  • 12
  • 30
Code Hunter
  • 10,075
  • 23
  • 72
  • 102

7 Answers7

94

I use shared_preferences plugin:

In pubspec.yaml

dependencies:
  flutter:
    sdk: flutter

  shared_preferences: ^0.4.3

And in dart file:

import 'dart:async';
import 'package:shared_preferences/shared_preferences.dart';
...
SharedPreferences preferences = await SharedPreferences.getInstance();
await preferences.clear();

I think this is what you need

Andrii Turkovskyi
  • 27,554
  • 16
  • 95
  • 105
41

You can simply use clear() function with your variable it will clear all the shared preferences.

SharedPreferences preferences = await SharedPreferences.getInstance();
await preferences.clear();

If you want to remove particular key value from shared preferences with key name you can do it like this way as follows.

SharedPreferences preferences = await SharedPreferences.getInstance();
await preferences.remove('KeyNameHere');
GaganSailor
  • 893
  • 2
  • 9
  • 19
17

try

final pref = await SharedPreferences.getInstance();
await pref.clear();
Sami Kanafani
  • 14,244
  • 6
  • 45
  • 41
3

Just try

prefManager = await SharedPreferences.getInstance();
await prefManager.clear();
Nickofthyme
  • 3,032
  • 23
  • 40
1

To Clear Shared Preferences Data

  1. You should import shared_preferences.dart

  2. write this code into the logout button

    onPressed: () { SharedPreferences userData = await SharedPreferences.getInstance(); await userData.clear(); }

1

To clear all shared preferences, try this:

SharedPreferences pref = await SharedPreferences.getInstance();
await pref.clear();

To clear particular key value, try this:

SharedPreferences pref = await SharedPreferences.getInstance();
await pref.remove('KeyNameHere');
1
final preferences = await SharedPreferences.getInstance();
await preferences.clear();
Lance Olana
  • 154
  • 1
  • 4
  • Remember that Stack Overflow isn't just intended to solve the immediate problem, but also to help future readers find solutions to similar problems, which requires understanding the underlying code. This is especially important for members of our community who are beginners, and not familiar with the syntax. Given that, **can you [edit] your answer to include an explanation of what you're doing** and why you believe it is the best approach? – Jeremy Caney Nov 18 '22 at 00:24