Skip to content

Instantly share code, notes, and snippets.

@TimurMukhortov
Last active February 24, 2021 17:45
Show Gist options
  • Select an option

  • Save TimurMukhortov/b462e0d866d5e8fa96c2b99150eecfa1 to your computer and use it in GitHub Desktop.

Select an option

Save TimurMukhortov/b462e0d866d5e8fa96c2b99150eecfa1 to your computer and use it in GitHub Desktop.
PreferenceUtils
import 'package:shared_preferences/shared_preferences.dart';
class PreferenceUtils {
static Future<SharedPreferences> get _instance async =>
_prefsInstance ??= await SharedPreferences.getInstance();
static SharedPreferences _prefsInstance;
/// Call this method from iniState() function of mainApp() fo create instance [PreferenceUtils]
static Future<SharedPreferences> init() async {
_prefsInstance = await _instance;
return _prefsInstance;
}
/// Use it when you need to check if data exists for a given key.
///
/// return true if storage contains value by given [key]
static Future<bool> containsKey(String key) async {
return _prefsInstance.containsKey(key);
}
static Future<String> getString(String key, [String defValue]) async {
return _prefsInstance.getString(key) ?? defValue ?? "";
}
static Future<bool> setString(String key, String value) async {
var prefs = await _instance;
return prefs?.setString(key, value) ?? Future.value(false);
}
static Future<bool> remove(String key) async {
if (_prefsInstance.containsKey(key)) {
return _prefsInstance.remove(key);
} else {
return true;
}
}
}
@TimurMukhortov
Copy link
Copy Markdown
Author

Gist for work with preference in flutter

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