Skip to content

Instantly share code, notes, and snippets.

@DevKhalyd
Last active July 3, 2021 22:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DevKhalyd/27e44a6b00bae219fe58191d4dd1dcd4 to your computer and use it in GitHub Desktop.
Save DevKhalyd/27e44a6b00bae219fe58191d4dd1dcd4 to your computer and use it in GitHub Desktop.
Shared preferences example
//yaml: shared_preferences:
//main.dart
void main() async {
WidgetsFlutterBinding.ensureInitialized();
final prefs = new MyShPrefs();
await prefs.initPrefs();
runApp(...);
//
class SharedPrefsManagerCustom {
static const _sessionToken = "session_token";
static final SharedPrefsManagerCustom _instance = SharedPrefsManagerCustom._internal();
factory SharedPrefsManagerCustom() => _instance;
SharedPrefsManagerCustom._internal();
static late SharedPreferences _prefs;
/// Call before to init the application
static Future initPrefs() async =>
_prefs = await SharedPreferences.getInstance();
// Functions
static Future<bool> clean() async => await _prefs.clear();
static set sessionToken(String? value) =>
_prefs.setString(_sessionToken, value ?? '');
/// This value can be empty
static String? get sessionToken => _prefs.getString(_sessionToken) ?? null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment