44 lines
1.2 KiB
Dart
44 lines
1.2 KiB
Dart
import 'package:get/get.dart';
|
||
import 'package:get_storage/get_storage.dart';
|
||
|
||
class StorageService extends GetxService {
|
||
late final GetStorage _box;
|
||
|
||
// 定义存储时使用的键名(Key)
|
||
static const String _tokenKey = 'user_token';
|
||
static const String _userIdKey = 'user_id';
|
||
|
||
// 提供一个静态的 'to' 方法,方便全局访问
|
||
static StorageService get to => Get.find();
|
||
|
||
// Service 初始化
|
||
Future<StorageService> init() async {
|
||
_box = GetStorage();
|
||
return this;
|
||
}
|
||
|
||
/// 判断是否已登录 (通过检查 token 是否存在且不为空)
|
||
bool get isLoggedIn =>
|
||
_box
|
||
.read<String?>(_tokenKey)
|
||
?.isNotEmpty ?? false;
|
||
|
||
/// 获取 Token
|
||
String? get token => _box.read<String?>(_tokenKey);
|
||
|
||
/// 获取 UserId
|
||
String? get userId => _box.read<String?>(_userIdKey);
|
||
|
||
/// 保存用户信息
|
||
Future<void> saveLoginInfo({required String token, required String userId}) async {
|
||
await _box.write(_tokenKey, token);
|
||
await _box.write(_userIdKey, userId);
|
||
}
|
||
|
||
/// 3. 删除用户信息 (用于退出登录)
|
||
Future<void> clearLoginInfo() async {
|
||
await _box.remove(_tokenKey);
|
||
await _box.remove(_userIdKey);
|
||
}
|
||
}
|