You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
105 lines
2.4 KiB
Dart
105 lines
2.4 KiB
Dart
import 'dart:convert';
|
|
|
|
import 'package:flutter/foundation.dart';
|
|
import 'package:get/get.dart';
|
|
import 'package:json_annotation/json_annotation.dart';
|
|
import 'package:shared_preferences/shared_preferences.dart';
|
|
|
|
part 'user.g.dart';
|
|
|
|
@JsonSerializable()
|
|
class UserInfo {
|
|
int userId;
|
|
String userName;
|
|
String? nickName;
|
|
String? avatarUrl;
|
|
|
|
UserInfo(
|
|
{required this.userId,
|
|
required this.userName,
|
|
this.nickName,
|
|
this.avatarUrl});
|
|
|
|
factory UserInfo.fromJson(Map<String, dynamic> json) =>
|
|
_$UserInfoFromJson(json);
|
|
|
|
Map<String, dynamic> toJson() => _$UserInfoToJson(this);
|
|
}
|
|
|
|
class UserController extends GetxController {
|
|
bool isReady = false;
|
|
|
|
var userId = 0.obs;
|
|
|
|
bool get isLoggedIn {
|
|
return userId.value > 0;
|
|
}
|
|
|
|
var userName = "".obs;
|
|
var nickName = "".obs;
|
|
var avatarUrl = "".obs;
|
|
|
|
String get getDisplayName {
|
|
return nickName.isNotEmpty ? nickName.string : userName.string;
|
|
}
|
|
|
|
Future<void> initialize() async {
|
|
if (!isReady) {
|
|
await loadFromStorage();
|
|
isReady = true;
|
|
|
|
postInit().catchError((err) {
|
|
if (kDebugMode) {
|
|
print(err);
|
|
}
|
|
});
|
|
}
|
|
}
|
|
|
|
Future<void> postInit() async {
|
|
await updateProfile();
|
|
}
|
|
|
|
/// 更新用户资料,并检测登录状态
|
|
Future<void> updateProfile() async {}
|
|
|
|
/// 从本地存储读取
|
|
Future<void> loadFromStorage() async {
|
|
try {
|
|
final prefs = await SharedPreferences.getInstance();
|
|
var userInfoJson = prefs.getString("userInfo");
|
|
if (userInfoJson == null) return;
|
|
|
|
var userInfoObject = jsonDecode(userInfoJson);
|
|
if (userInfoObject == null) return;
|
|
|
|
var userInfo = UserInfo.fromJson(userInfoObject);
|
|
|
|
userId.value = userInfo.userId;
|
|
userName.value = userInfo.userName;
|
|
nickName.value = userInfo.nickName ?? "";
|
|
avatarUrl.value = userInfo.avatarUrl ?? "";
|
|
} catch (ex) {
|
|
if (kDebugMode) {
|
|
print(ex);
|
|
}
|
|
}
|
|
}
|
|
|
|
/// 保存到本地存储
|
|
Future<void> saveToStorage() async {
|
|
final prefs = await SharedPreferences.getInstance();
|
|
|
|
var userInfo = UserInfo(
|
|
userId: userId.value,
|
|
userName: userName.value,
|
|
nickName: nickName.isNotEmpty ? nickName.value : null,
|
|
avatarUrl: avatarUrl.isNotEmpty ? avatarUrl.value : null,
|
|
);
|
|
|
|
var userInfoJson = jsonEncode(userInfo.toJson());
|
|
|
|
prefs.setString("userInfo", userInfoJson);
|
|
}
|
|
}
|