user_util.dart
1.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:wow_english/common/core/sp_const.dart';
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 {
static UserEntity? _userEntity;
static String get token => _userEntity?.token ?? '';
static void saveUser(UserEntity user) {
_userEntity = user;
_saveUserJson(user.toString());
}
static UserEntity? getUser() {
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();
}
}
}
return _userEntity;
}
static void _saveUserJson(String userJson) {
SpUtil.getInstance().setData(SpConst.prefsKeyUserInfo, userJson);
}
static String? _getUserJson() {
return SpUtil.getInstance().get<String>(SpConst.prefsKeyUserInfo);
}
static void _clearUserData() {
_userEntity = null;
SpUtil.getInstance().remove(SpConst.prefsKeyUserInfo);
}
static void logout() {
_clearUserData();
Navigator.of(AppRouter.context).pushNamedAndRemoveUntil(AppRouteName.login, (route) => false);
}
}