mirror of
https://gitlab.com/comunic/comunicmobile
synced 2024-12-27 05:18:50 +00:00
81 lines
2.2 KiB
Dart
81 lines
2.2 KiB
Dart
import 'dart:convert';
|
|
|
|
import 'package:comunic/models/login_tokens.dart';
|
|
import 'package:shared_preferences/shared_preferences.dart';
|
|
|
|
/// Preferences helper
|
|
///
|
|
/// Stores current account tokens
|
|
///
|
|
/// @author Pierre HUBERT
|
|
|
|
enum PreferencesKeyList { LOGIN_TOKENS, ENABLE_DARK_THEME }
|
|
|
|
const _PreferenceKeysName = {
|
|
PreferencesKeyList.LOGIN_TOKENS: "login_tokens",
|
|
PreferencesKeyList.ENABLE_DARK_THEME: "dark_theme",
|
|
};
|
|
|
|
class PreferencesHelper {
|
|
static PreferencesHelper _instance;
|
|
|
|
static Future<PreferencesHelper> getInstance() async {
|
|
if (_instance == null) {
|
|
_instance = PreferencesHelper._();
|
|
await _init();
|
|
}
|
|
|
|
return _instance;
|
|
}
|
|
|
|
static SharedPreferences _sharedPreferences;
|
|
|
|
PreferencesHelper._();
|
|
|
|
static Future<void> _init() async {
|
|
_sharedPreferences = await SharedPreferences.getInstance();
|
|
}
|
|
|
|
/// Set new login tokens
|
|
Future<void> setLoginTokens(LoginTokens tokens) async {
|
|
await setString(PreferencesKeyList.LOGIN_TOKENS,
|
|
tokens == null ? "null" : tokens.toString());
|
|
}
|
|
|
|
/// Get current [LoginTokens]. Returns null if none or in case of failure
|
|
LoginTokens getLoginTokens() {
|
|
try {
|
|
final string = getString(PreferencesKeyList.LOGIN_TOKENS);
|
|
if (string == null || string == "null") return null;
|
|
return LoginTokens.fromJSON(jsonDecode(string));
|
|
} on Exception catch (e) {
|
|
print(e.toString());
|
|
return null;
|
|
}
|
|
}
|
|
|
|
Future<bool> setString(PreferencesKeyList key, String value) async {
|
|
return await _sharedPreferences.setString(_PreferenceKeysName[key], value);
|
|
}
|
|
|
|
String getString(PreferencesKeyList key) {
|
|
return _sharedPreferences.getString(_PreferenceKeysName[key]);
|
|
}
|
|
|
|
Future<bool> setBool(PreferencesKeyList key, bool value) async {
|
|
return await _sharedPreferences.setBool(_PreferenceKeysName[key], value);
|
|
}
|
|
|
|
bool getBool(PreferencesKeyList key, {bool alternative = false}) {
|
|
final v = _sharedPreferences.getBool(_PreferenceKeysName[key]);
|
|
return v == null ? alternative : v;
|
|
}
|
|
}
|
|
|
|
PreferencesHelper preferences() {
|
|
if (PreferencesHelper._instance == null)
|
|
throw Exception("Try to get preference before their initialization!");
|
|
|
|
return PreferencesHelper._instance;
|
|
}
|