1
0
mirror of https://gitlab.com/comunic/comunicmobile synced 2025-02-18 22:52:39 +00:00
comunicmobile/lib/helpers/preferences_helper.dart

50 lines
1.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
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 _sharedPreferences.setString(
"login_tokens", tokens == null ? "null" : tokens.toString());
}
/// Get current [LoginTokens]. Returns null if none or in case of failure
LoginTokens getLoginTokens() {
try {
final string = _sharedPreferences.getString("login_tokens");
if (string == null || string == "null") return null;
return LoginTokens.fromJSON(jsonDecode(string));
} on Exception catch (e) {
print(e.toString());
return null;
}
}
}