user_util.dart
2.38 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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.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 void saveUser(UserEntity? user) {
if (user == null) {
_clearUserData();
return;
}
_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([bool showPasswordLoginPage = false]) {
_clearUserData();
// 判断下不在Splash页就跳转
/*var currentPageName = ModalRoute.of(AppRouter.context)?.settings.name;
Log.d('当前页面:$currentPageName');
if (currentPageName != AppRouteName.splash) {
Navigator.of(AppRouter.context).pushNamedAndRemoveUntil(AppRouteName.login, (route) => false);
}*/
pushNamedAndRemoveUntil(AppRouteName.login, (route) => false, arguments: {'showPasswordPage': showPasswordLoginPage});
}
// 是否有游戏权限
static bool hasGamePermission() {
return _userEntity?.valid ?? false;
}
// 是否登录(token是否有效)
static bool isLogined() {
return getUserToken().isNotEmpty;
}
static String getUserToken() {
return _userEntity?.token ?? '';
}
// (vip)剩余有效期
static int getRemainingValidity() {
return _userEntity?.validDay ?? 0;
}
}