user_service.dart 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import 'dart:core';
  2. import 'package:domain/entity/response/hotel_info_entity.dart';
  3. import 'package:domain/repository/auth_repository.dart';
  4. import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
  5. import 'package:get/get.dart';
  6. import 'package:plugin_platform/engine/sp/sp_util.dart';
  7. import 'package:shared/utils/event_bus.dart';
  8. import 'package:shared/utils/log_utils.dart';
  9. import 'package:shared/utils/util.dart';
  10. import '../constants/app_constant.dart';
  11. /// 用户相关的单例服务,保存了Token,UserProfile等信息
  12. class UserService extends GetxService {
  13. static UserService get to => Get.find();
  14. final AuthRepository _authRepository;
  15. UserService(this._authRepository);
  16. //用户登录Token
  17. String? token;
  18. //用户是否已经登录 - 可变字段
  19. Rx<bool> haslogin = false.obs;
  20. //用户详情信息 - 可变字段
  21. Rx<HotelInfoEntity> hotelInfo = HotelInfoEntity().obs;
  22. //极光推送的 registrationId - 可变字段
  23. RxString registrationId = ''.obs;
  24. //当前用户的未读消息数量
  25. RxInt unreadNotificationsCount = 0.obs;
  26. bool get hasToken => token?.isNotEmpty ?? false;
  27. bool get isLogin => haslogin.value;
  28. HotelInfoEntity get getHotelInfo => hotelInfo.value;
  29. String get getRegistrationId => registrationId.value;
  30. int get getUnreadNotificationsCount => unreadNotificationsCount.value;
  31. /// 设置全局的Token,同时更新 hasLogin 的值,赋值时机如下
  32. /*
  33. 1. 在登录或注册成功的时候赋值
  34. 2. 在main.dart中初始化的时候查询是否有Token,如果有的话需要赋值
  35. 3. 退出登录的时候需要赋值
  36. */
  37. void setToken(String? token) {
  38. this.token = token;
  39. if (Utils.isEmpty(token)) {
  40. haslogin.value = false;
  41. SPUtil.remove(AppConstant.storageToken);
  42. } else {
  43. haslogin.value = true;
  44. SPUtil.putString(AppConstant.storageToken, token!);
  45. }
  46. Log.d('UserService =========> 设置Token为:$token');
  47. }
  48. /// 处理退出登录之后的数据清除
  49. void handleLogoutParams() {
  50. SPUtil.remove(AppConstant.storageToken);
  51. SPUtil.remove(AppConstant.storageIsAdmin);
  52. haslogin.value = false;
  53. hotelInfo.value = HotelInfoEntity();
  54. }
  55. @override
  56. void onInit() {
  57. super.onInit();
  58. String? token = SPUtil.getString(AppConstant.storageToken);
  59. Log.d('UserService - 查询SP token:$token 并赋值' );
  60. setToken(token);
  61. }
  62. }