Files
ln-ios/ln_jq_app/lib/storage_service.dart
2025-11-05 13:14:01 +08:00

77 lines
2.1 KiB
Dart
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';
/// 定义登录渠道的枚举类型
enum LoginChannel {
station, // 站点
driver, // 司机
none, // 未登录或未知
}
class StorageService extends GetxService {
late final GetStorage _box;
// --- 定义存储时使用的键名 (Key) ---
static const String _tokenKey = 'user_token';
static const String _userIdKey = 'user_id';
// 定义登录渠道的存储键名
static const String _channelKey = 'login_channel';
// 提供一个静态的 'to' 方法,方便全局访问
static StorageService get to => Get.find();
// Service 初始化
Future<StorageService> init() async {
_box = GetStorage();
return this;
}
/// --- Getter 方法,用于读取状态 ---
/// 判断是否已登录 (通过检查 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);
///获取当前登录渠道
/// 从存储中读取字符串,并转换为枚举类型
LoginChannel get loginChannel {
final channelString = _box.read<String?>(_channelKey);
if (channelString == 'station') {
return LoginChannel.station;
} else if (channelString == 'driver') {
return LoginChannel.driver;
}
return LoginChannel.none;
}
/// --- 操作方法 ---
/// 保存用户信息
/// @param channel - 登录渠道station 或 driver
Future<void> saveLoginInfo({
required String token,
required String userId,
required String channel, // 接收一个字符串类型的渠道
}) async {
await _box.write(_tokenKey, token);
await _box.write(_userIdKey, userId);
// 将渠道字符串存入本地
await _box.write(_channelKey, channel);
}
///删除用户信息,增加删除渠道信息
Future<void> clearLoginInfo() async {
await _box.remove(_tokenKey);
await _box.remove(_userIdKey);
// 退出登录时,一并清除渠道信息
await _box.remove(_channelKey);
}
}