Skip to content

Commit

Permalink
fix login\logout\server status check logic
Browse files Browse the repository at this point in the history
  • Loading branch information
clssw1004 committed Dec 12, 2024
1 parent dd56ce6 commit 1c61969
Show file tree
Hide file tree
Showing 5 changed files with 62 additions and 58 deletions.
14 changes: 9 additions & 5 deletions lib/constants/storage_keys.dart
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,19 @@ class StorageKeys {
// 主题相关
static const String themeMode = 'theme_mode';
static const String themeColor = 'theme_color';

// 语言相关
static const String locale = 'locale';
static const String timezone = 'timezone';

// 服务器相关
static const String serverUrl = 'server_url';

// 用户相关
static const String token = 'token';
static const String userId = 'userId';
static const String username = 'username';

// 账本相关
static const String defaultBookId = 'default_book_id';
static const String lastUsedBookId = 'last_used_book_id';
Expand All @@ -34,6 +34,10 @@ class StorageKeys {
// 筛选面板相关
static const String filterPanelPinned = 'filter_panel_pinned';

// 服务器配置相关
static const String serverConfigs = 'server_configs';
static const String selectedServerId = 'selected_server_id';

// 禁止实例化
StorageKeys._();
}
}
11 changes: 6 additions & 5 deletions lib/main.dart
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ class _ServerCheckScreenState extends State<ServerCheckScreen> {
// 设置较短的超时时间
await Future.any([
ApiService.checkServerStatus(),
Future.delayed(const Duration(seconds: 3), () {
Future.delayed(const Duration(seconds: 5), () {
throw TimeoutException('Server check timeout');
}),
]);
Expand Down Expand Up @@ -128,7 +128,6 @@ class _ServerCheckScreenState extends State<ServerCheckScreen> {
if (snapshot.connectionState == ConnectionState.waiting) {
return _buildLoadingScreen(context);
}

// 如果没有服务器配置或服务器检查失败
if (snapshot.data != true) {
// 如果没有服务器配置,直接跳转登录页
Expand All @@ -145,7 +144,9 @@ class _ServerCheckScreenState extends State<ServerCheckScreen> {

// 服务器正常,检查会话状态
return FutureBuilder<bool>(
future: UserService.hasValidSession(),
future: StorageService.getString(StorageKeys.token).isEmpty
? Future.value(false) // 如果没有 token,直接返回 false
: UserService.hasValidSession(), // 有 token 才去验证会话
builder: (context, sessionSnapshot) {
if (sessionSnapshot.connectionState == ConnectionState.waiting) {
return _buildLoadingScreen(context);
Expand Down Expand Up @@ -176,7 +177,7 @@ class _ServerCheckScreenState extends State<ServerCheckScreen> {
child: Column(
children: [
Image.asset(
'assets/images/logo.png',
'assets/images/app_logo.png',
width: 120,
height: 120,
),
Expand Down Expand Up @@ -227,7 +228,7 @@ Future<void> main() async {
await UserService.init();

final prefs = await SharedPreferences.getInstance();
final serverConfigService = ServerConfigService(prefs);
final serverConfigService = ServerConfigService();

// 初始化主题
final themeProvider = ThemeProvider();
Expand Down
13 changes: 6 additions & 7 deletions lib/pages/settings/widgets/logout_button.dart
Original file line number Diff line number Diff line change
Expand Up @@ -61,13 +61,12 @@ class LogoutButton extends StatelessWidget {
),
),
TextButton(
onPressed: () {
UserService.logout();
Navigator.pushNamedAndRemoveUntil(
context,
'/login',
(route) => false,
);
onPressed: () async {
Navigator.pop(context);
await UserService.logout();
if (context.mounted) {
Navigator.of(context).pushReplacementNamed('/login');
}
},
child: Text(
l10n.confirm,
Expand Down
49 changes: 24 additions & 25 deletions lib/pages/settings/widgets/user_card.dart
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import 'package:flutter/material.dart';
import '../../../utils/api_error_handler.dart';
import '../../../services/api_service.dart';
import '../../user/user_info_page.dart';

class UserCard extends StatefulWidget {
const UserCard({Key? key}) : super(key: key);
Expand All @@ -16,36 +17,29 @@ class _UserCardState extends State<UserCard> {
@override
void initState() {
super.initState();
_loadUserInfo();
_refreshUserInfo();
}

Future<void> _loadUserInfo() async {
try {
final userInfo = await ApiErrorHandler.wrapRequest(
context,
() => ApiService.getUserInfo(),
);
Future<void> _refreshUserInfo() async {
if (!mounted) return;

if (mounted) {
setState(() {
_userInfo = userInfo;
_isLoading = false;
});
}
setState(() => _isLoading = true);
try {
final userInfo = await ApiService.getUserInfo();
if (!mounted) return;
setState(() {
_userInfo = userInfo;
_isLoading = false;
});
} catch (e) {
if (mounted) {
setState(() {
_userInfo = null;
_isLoading = false;
});
}
if (!mounted) return;
setState(() {
_userInfo = null;
_isLoading = false;
});
}
}

void _refreshUserInfo() {
_loadUserInfo();
}

@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
Expand Down Expand Up @@ -85,8 +79,13 @@ class _UserCardState extends State<UserCard> {
clipBehavior: Clip.antiAlias,
child: InkWell(
onTap: () {
Navigator.pushNamed(context, '/user-info').then((_) {
_refreshUserInfo();
final route = MaterialPageRoute(
builder: (_) => UserInfoPage(),
);
Navigator.push(context, route).then((value) {
if (mounted && ModalRoute.of(context)?.isCurrent == true) {
_refreshUserInfo();
}
});
},
child: Container(
Expand Down
33 changes: 17 additions & 16 deletions lib/services/server_config_service.dart
Original file line number Diff line number Diff line change
@@ -1,16 +1,15 @@
import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
import '../models/server_config.dart';
import '../constants/storage_keys.dart';
import './storage_service.dart';

class ServerConfigService {
static const String _storageKey = 'server_configs';
final SharedPreferences _prefs;

ServerConfigService(this._prefs);
static const String _configsKey = StorageKeys.serverConfigs;
static const String _selectedConfigKey = StorageKeys.selectedServerId;

Future<List<ServerConfig>> getConfigs() async {
final String? jsonStr = _prefs.getString(_storageKey);
if (jsonStr == null) return [];
final String? jsonStr = StorageService.getString(_configsKey);
if (jsonStr!.isEmpty) return [];

final List<dynamic> jsonList = json.decode(jsonStr);
return jsonList
Expand All @@ -20,7 +19,7 @@ class ServerConfigService {

Future<void> saveConfigs(List<ServerConfig> configs) async {
final jsonList = configs.map((config) => config.toJson()).toList();
await _prefs.setString(_storageKey, json.encode(jsonList));
await StorageService.setString(_configsKey, json.encode(jsonList));
}

Future<void> addConfig(ServerConfig config) async {
Expand All @@ -45,17 +44,19 @@ class ServerConfigService {
}

Future<ServerConfig?> getSelectedConfig() async {
final String? selectedId = _prefs.getString('selected_server_id');
if (selectedId == null) return null;
final String selectedId = StorageService.getString(_selectedConfigKey);
if (selectedId.isEmpty) return null;

final configs = await getConfigs();
return configs.firstWhere(
(config) => config.id == selectedId,
orElse: () => configs.first,
);
return configs.isEmpty
? null
: configs.firstWhere(
(config) => config.id == selectedId,
orElse: () => configs.first,
);
}

Future<void> setSelectedConfig(String id) async {
await _prefs.setString('selected_server_id', id);
await StorageService.setString(_selectedConfigKey, id);
}
}
}

0 comments on commit 1c61969

Please sign in to comment.