基础库
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

user_info_model_notifier.dart 2.0 KiB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import 'dart:convert';
  2. import 'package:flutter/material.dart';
  3. import 'package:zhiying_comm/models/user/user_info_model.dart';
  4. import 'package:zhiying_comm/util/global_config.dart';
  5. import 'package:zhiying_comm/util/log/let_log.dart';
  6. import 'package:zhiying_comm/util/shared_prefe_util.dart';
  7. ///
  8. /// 用户信息Provider
  9. ///
  10. class UserInfoNotifier with ChangeNotifier {
  11. /// 用户信息
  12. UserInfoModel _userInfo;
  13. UserInfoModel get userInfo {
  14. if (null == _userInfo) {
  15. getUserInfoModel().then((user) {
  16. if (user != null) {
  17. _userInfo = user;
  18. notifyListeners();
  19. }
  20. });
  21. }
  22. return _userInfo;
  23. }
  24. /// 更新用户数据
  25. void setUserInfo(UserInfoModel loginUser) async {
  26. print('${loginUser.toString()}');
  27. this._userInfo = loginUser;
  28. // 缓存数据
  29. await SharedPreferencesUtil.setStringValue(
  30. GlobalConfig.SHARED_KEY_TOKEN, loginUser.token);
  31. await SharedPreferencesUtil.setStringValue(
  32. GlobalConfig.SHARED_KEY_MOBILE, loginUser.mobile);
  33. await SharedPreferencesUtil.setStringValue(
  34. GlobalConfig.SHARED_KEY_USER_INFO, jsonEncode(loginUser.toJson()));
  35. notifyListeners();
  36. }
  37. /// 退出登陆
  38. void unLogin() async {
  39. this._userInfo = null;
  40. // 清除缓存数据
  41. await SharedPreferencesUtil.setStringValue(
  42. GlobalConfig.SHARED_KEY_TOKEN, '');
  43. await SharedPreferencesUtil.setStringValue(
  44. GlobalConfig.SHARED_KEY_MOBILE, '');
  45. await SharedPreferencesUtil.setStringValue(
  46. GlobalConfig.SHARED_KEY_USER_INFO, '');
  47. notifyListeners();
  48. }
  49. /// 获取登陆数据
  50. Future<UserInfoModel> getUserInfoModel() async {
  51. if (null != _userInfo) {
  52. return _userInfo;
  53. }
  54. try {
  55. String userInfoJson = await SharedPreferencesUtil.getStringValue(
  56. GlobalConfig.SHARED_KEY_USER_INFO);
  57. _userInfo = UserInfoModel.fromJson(jsonDecode(userInfoJson));
  58. } catch (e) {
  59. Logger.log(e);
  60. }
  61. return _userInfo;
  62. }
  63. }