hmawla

Dart Session Example

Jul 30th, 2021 (edited)
826
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. class Session {
  2.   static final Session _session = Session._internal();
  3.  
  4.   factory Session() {
  5.     return _session;
  6.   }
  7.  
  8.   Session._internal() {
  9.     //Initialize what you need here
  10.   }
  11.  
  12.   // Example session properties
  13.   User _loggedInUser;
  14.   String accessToken;
  15.   AppDatabase _appDatabase;
  16.  
  17.   //Example API client and its getter prop
  18.   ApiClient _apiClient = new ApiClient();
  19.   ApiClient get apiClient => _apiClient;
  20.  
  21.   // Example get logged in user logic
  22.   Future<User> getLoggedInUser() async {
  23.     if (_loggedInUser != null) return _loggedInUser;
  24.     try {
  25.       _loggedInUser = await apiClient.getLoggedInUser();
  26.       return _loggedInUser;
  27.     } catch (error) {
  28.       throw error;
  29.     }
  30.   }
  31.  
  32.   // Example logout logic
  33.   void logout(BuildContext context) {
  34.     SharedPreferences.getInstance().then((prefs) {
  35.       prefs.remove('accessToken');
  36.       _loggedInUser = null;
  37.       Navigator.of(context).pushReplacementNamed('/login');
  38.     });
  39.   }
  40.  
  41.   // Example database logic
  42.   Future<AppDatabase> getDatabaseInstance() async {
  43.     if (_appDatabase != null) return _appDatabase;
  44.  
  45.     _appDatabase = await $FloorAppDatabase
  46.         .databaseBuilder('app_database.db')
  47.         .addMigrations([
  48.       AppDatabase.migration1to2,
  49.       AppDatabase.migration2to3,
  50.       AppDatabase.migration3to4,
  51.       AppDatabase.migration4to5,
  52.     ]).build();
  53.     return _appDatabase;
  54.   }
  55. }
  56.  
  57. //USAGE
  58. Session().getLoggedInUser().then();
  59.  
  60. Session().apiClient.login({username: '', password: ''}).then();
  61.  
  62. Session().getDatabaseInstance().getDatabaseInstance().addRecord(record).then();
  63.  
  64. Session().accessToken = 'access token string';
RAW Paste Data