Last active
February 24, 2021 17:45
-
-
Save TimurMukhortov/b462e0d866d5e8fa96c2b99150eecfa1 to your computer and use it in GitHub Desktop.
PreferenceUtils
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Gist for work with preference in flutter