Blame view

lib/common/core/user_util.dart 1.56 KB
94342c3f   Key   feat: user util
1
2
  import 'dart:convert';
  
aa4e28be   Key   removed: cache_bl...
3
  import 'package:flutter/foundation.dart';
94342c3f   Key   feat: user util
4
  import 'package:flutter/material.dart';
e12dbc82   Key   user module
5
  import 'package:wow_english/common/core/sp_const.dart';
94342c3f   Key   feat: user util
6
7
8
9
10
  import 'package:wow_english/models/user_entity.dart';
  import 'package:wow_english/route/route.dart';
  import 'package:wow_english/utils/sp_util.dart';
  
  class UserUtil {
aa4e28be   Key   removed: cache_bl...
11
12
13
    static UserEntity? _userEntity;
  
    static String get token => _userEntity?.token ?? '';
94342c3f   Key   feat: user util
14
  
089ccd5c   Key   fixed: user util ...
15
    static void saveUser(UserEntity user) {
aa4e28be   Key   removed: cache_bl...
16
17
      _userEntity = user;
      _saveUserJson(user.toString());
94342c3f   Key   feat: user util
18
19
20
    }
  
    static UserEntity? getUser() {
aa4e28be   Key   removed: cache_bl...
21
22
23
24
25
26
27
28
29
30
31
32
33
      if (_userEntity == null) {
        String? userJson = _getUserJson();
        if (userJson != null && userJson.isNotEmpty) {
          try {
            var userEntity = UserEntity.fromJson(json.decode(userJson));
            // todo 并且在有效期,计算一下, "expireTime": 2592000 倒计时需要手动转换,后面再优化
            _userEntity = userEntity;
          } catch (e) {
            if (kDebugMode) {
              print(e);
            }
            _clearUserData();
          }
94342c3f   Key   feat: user util
34
35
        }
      }
aa4e28be   Key   removed: cache_bl...
36
      return _userEntity;
94342c3f   Key   feat: user util
37
38
    }
  
aa4e28be   Key   removed: cache_bl...
39
    static void _saveUserJson(String userJson) {
94342c3f   Key   feat: user util
40
41
42
      SpUtil.getInstance().setData(SpConst.prefsKeyUserInfo, userJson);
    }
  
aa4e28be   Key   removed: cache_bl...
43
    static String? _getUserJson() {
94342c3f   Key   feat: user util
44
45
46
      return SpUtil.getInstance().get<String>(SpConst.prefsKeyUserInfo);
    }
  
aa4e28be   Key   removed: cache_bl...
47
48
    static void _clearUserData() {
      _userEntity = null;
94342c3f   Key   feat: user util
49
50
51
      SpUtil.getInstance().remove(SpConst.prefsKeyUserInfo);
    }
  
089ccd5c   Key   fixed: user util ...
52
    static void logout() {
aa4e28be   Key   removed: cache_bl...
53
      _clearUserData();
99efc573   Key   兼容非json response ...
54
      Navigator.of(AppRouter.context).pushNamedAndRemoveUntil(AppRouteName.login, (route) => false);
94342c3f   Key   feat: user util
55
56
    }
  }