Skip to content

Instantly share code, notes, and snippets.

@faisalraja
Created January 17, 2019 03:03
Show Gist options
  • Save faisalraja/9b628439978c67b2fb6515cf202a3992 to your computer and use it in GitHub Desktop.
Save faisalraja/9b628439978c67b2fb6515cf202a3992 to your computer and use it in GitHub Desktop.
SharedPreference helper for flutter
class Preference {
static SharedPreferences _prefs;
static Map<String, dynamic> _memoryPrefs = Map<String, dynamic>();
static Future<SharedPreferences> load() async {
if (_prefs == null) {
_prefs = await SharedPreferences.getInstance();
}
return _prefs;
}
static void setString(String key, String value) {
_prefs.setString(key, value);
_memoryPrefs[key] = value;
}
static void setInt(String key, int value) {
_prefs.setInt(key, value);
_memoryPrefs[key] = value;
}
static void setDouble(String key, double value) {
_prefs.setDouble(key, value);
_memoryPrefs[key] = value;
}
static void setBool(String key, bool value) {
_prefs.setBool(key, value);
_memoryPrefs[key] = value;
}
static String getString(String key, {String def}) {
String val;
if (_memoryPrefs.containsKey(key)) {
val = _memoryPrefs[key];
}
if (val == null) {
val = _prefs.getString(key);
}
if (val == null) {
val = def;
}
_memoryPrefs[key] = val;
return val;
}
static int getInt(String key, {int def}) {
int val;
if (_memoryPrefs.containsKey(key)) {
val = _memoryPrefs[key];
}
if (val == null) {
val = _prefs.getInt(key);
}
if (val == null) {
val = def;
}
_memoryPrefs[key] = val;
return val;
}
static double getDouble(String key, {double def}) {
double val;
if (_memoryPrefs.containsKey(key)) {
val = _memoryPrefs[key];
}
if (val == null) {
val = _prefs.getDouble(key);
}
if (val == null) {
val = def;
}
_memoryPrefs[key] = val;
return val;
}
static bool getBool(String key, {bool def = false}) {
bool val;
if (_memoryPrefs.containsKey(key)) {
val = _memoryPrefs[key];
}
if (val == null) {
val = _prefs.getBool(key);
}
if (val == null) {
val = def;
}
_memoryPrefs[key] = val;
return val;
}
}
@00Adnan00
Copy link

00Adnan00 commented Feb 27, 2023

static Future<SharedPreferences> load() async {
    _prefs = await SharedPreferences.getInstance();
    final keys = _prefs.getKeys();
    for (String key in keys) {
      _memoryPrefs[key] = _prefs.get(key);
    }
    return _prefs;
  }

@keehyun2 It's much better now, I added this to load function

@sixtusagbo
Copy link

sixtusagbo commented Mar 28, 2023

class Preferences {
  // ...

  static void setStringList(String key, List<String> value) {
      _prefs.setStringList(key, value);
      _memoryPrefs[key] = value;
    }
  
    static void remove(String key) {
      _prefs.remove(key);
      _memoryPrefs.remove(key);
    }

    static List<String>? getStringList(String key) => _memoryPrefs[key] ?? _prefs.getStringList(key);

   // ...
}

I added the above methods

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment