yodeput

preferences.dart

Sep 22nd, 2020
859
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import 'dart:convert';
  2.  
  3. import 'package:nmapp/models/token.dart';
  4. import 'package:nmapp/models/user_data.dart';
  5. import 'package:shared_preferences/shared_preferences.dart';
  6.  
  7. class Preferences {
  8.   static SharedPreferences _preferences;
  9.   static Preferences _pref;
  10.  
  11.   static Future getInstance() async {
  12.     if (_pref == null) {
  13.       var secureStorage = Preferences._();
  14.       await secureStorage._init();
  15.       _pref = secureStorage;
  16.     }
  17.     return _pref;
  18.   }
  19.  
  20.   Future _init() async {
  21.     _preferences = await SharedPreferences.getInstance();
  22.   }
  23.  
  24.   Preferences._();
  25.  
  26.   static const String is_logged_in = "isLoggedIn";
  27.   static const String auth_token = "authToken";
  28.   static const String userData = "userData";
  29.  
  30.   static const String is_dark_mode = "is_dark_mode";
  31.   static const String current_language = "current_language";
  32.  
  33.   static void clearData() {
  34.     _preferences.clear();
  35.   }
  36.  
  37.   static void setLogin({Token token}) {
  38.     _preferences.setString(Preferences.auth_token, token.token);
  39.     _preferences.setString(
  40.         Preferences.userData, jsonEncode(token.userData.toJson()));
  41.     _preferences.setBool(Preferences.is_logged_in, true);
  42.   }
  43.  
  44.   static void setUserData({UserData data}) {
  45.     _preferences.setString(Preferences.userData, jsonEncode(data.toJson()));
  46.   }
  47.  
  48.   static bool isLogedin() {
  49.     return _preferences.getBool(Preferences.is_logged_in) ?? false;
  50.   }
  51.  
  52.   static String getToken() {
  53.     return _preferences.getString(Preferences.auth_token);
  54.   }
  55.  
  56.   static UserData getUserData() {
  57.     return UserData.fromJsonMap(
  58.         jsonDecode(_preferences.getString(Preferences.userData)));
  59.   }
  60. }
  61.  
RAW Paste Data