user_manager.dart 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. import 'dart:convert';
  2. import 'package:shuqi/utility/event_bus.dart';
  3. import 'package:shuqi/model/constant.dart';
  4. const String EventUserLogin = 'EventUserLogin';
  5. const String EventUserLogout = 'EventUserLogout';
  6. class UserManager {
  7. static UserManager instance = UserManager();
  8. User? user;
  9. static User? get currentUser {
  10. return UserManager.instance.user;
  11. }
  12. logout() {
  13. this.user = null;
  14. preferences.remove('user');
  15. eventBus.emit(EventUserLogout);
  16. }
  17. login(Map<String, dynamic> userJson) {
  18. var user = User.fromJson(userJson);
  19. this.user = user;
  20. saveUser();
  21. eventBus.emit(EventUserLogin);
  22. }
  23. bool get isLogin {
  24. return user != null;
  25. }
  26. loadUserFromLocal() {
  27. String? userJson = preferences.getString('user');
  28. if (userJson != null) {
  29. user = User.fromJson(json.decode(userJson));
  30. }
  31. }
  32. void saveUser() async {
  33. var data = json.encode(user);
  34. preferences.setString('user', data);
  35. }
  36. }
  37. class User {
  38. late String token;
  39. late int id;
  40. late String nickname;
  41. late String avatarUrl;
  42. late bool isVip;
  43. late double wealth;
  44. late int coupon;
  45. late int monthlyTicket;
  46. User.fromJson(Map json) {
  47. token = json['token'];
  48. id = json['id'];
  49. nickname = json['nickname'];
  50. avatarUrl = json['avatar'];
  51. isVip = json['is_vip'] == 1;
  52. wealth = json['wealth'];
  53. coupon = json['coupon'];
  54. monthlyTicket = json['ticket'];
  55. }
  56. Map<String, dynamic> toJson() {
  57. return {
  58. 'token': token,
  59. 'id': id,
  60. 'nickname': nickname,
  61. 'avatar': avatarUrl,
  62. 'is_vip': isVip ? 1 : 0,
  63. 'wealth': wealth,
  64. 'coupon': coupon,
  65. 'ticket': monthlyTicket,
  66. };
  67. }
  68. }