fix: token过期自动跳转登录页
- dio_client.dart: 401错误时触发onUnauthorized回调 - main.dart: 连接回调到AuthProvider.forceLogout - 完整链路: 401 -> 清除token -> 强制登出 -> 显示LoginPage
This commit is contained in:
@@ -37,6 +37,6 @@ _flutter.buildConfig = {"engineRevision":"e4b8dca3f1b4ede4c30371002441c88c12187e
|
||||
|
||||
_flutter.loader.load({
|
||||
serviceWorkerSettings: {
|
||||
serviceWorkerVersion: "2359170310" /* Flutter's service worker is deprecated and will be removed in a future Flutter release. */
|
||||
serviceWorkerVersion: "806880865" /* Flutter's service worker is deprecated and will be removed in a future Flutter release. */
|
||||
}
|
||||
});
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -17,6 +17,9 @@ class NetworkConfig {
|
||||
class DioClient {
|
||||
late final Dio _dio;
|
||||
|
||||
/// 未授权回调(token 过期时触发)
|
||||
VoidCallback? onUnauthorized;
|
||||
|
||||
DioClient() {
|
||||
_dio = _createDio();
|
||||
_setupInterceptors();
|
||||
@@ -92,7 +95,13 @@ class DioClient {
|
||||
) {
|
||||
final data = response.data;
|
||||
if (data is Map<String, dynamic>) {
|
||||
return ApiResponse.fromJson(data, fromJson);
|
||||
final apiResponse = ApiResponse.fromJson(data, fromJson);
|
||||
// 检测业务层未授权(后端返回 HTTP 200 + code "0002")
|
||||
if (apiResponse.isUnauthorized) {
|
||||
LocalStorage.clearUserData();
|
||||
onUnauthorized?.call();
|
||||
}
|
||||
return apiResponse;
|
||||
}
|
||||
return ApiResponse.fail('响应数据格式错误');
|
||||
}
|
||||
@@ -109,6 +118,7 @@ class DioClient {
|
||||
|
||||
if (_isUnauthorized(e)) {
|
||||
_clearUserData();
|
||||
onUnauthorized?.call();
|
||||
return ApiResponse.unauthorized('登录已过期,请重新登录');
|
||||
}
|
||||
|
||||
|
||||
@@ -94,7 +94,12 @@ class MyApp extends StatelessWidget {
|
||||
Provider<BonusService>(create: (_) => BonusService(dioClient)),
|
||||
// State Management
|
||||
ChangeNotifierProvider<AuthProvider>(
|
||||
create: (ctx) => AuthProvider(ctx.read<UserService>()),
|
||||
create: (ctx) {
|
||||
final authProvider = AuthProvider(ctx.read<UserService>());
|
||||
// token 过期时,DioClient 回调 AuthProvider 强制登出
|
||||
dioClient.onUnauthorized = authProvider.forceLogout;
|
||||
return authProvider;
|
||||
},
|
||||
),
|
||||
ChangeNotifierProvider<MarketProvider>(
|
||||
create: (ctx) => MarketProvider(ctx.read<MarketService>()),
|
||||
|
||||
@@ -119,6 +119,12 @@ class AuthProvider extends ChangeNotifier {
|
||||
_isLoggedIn = false;
|
||||
}
|
||||
|
||||
/// 强制登出(token 过期时由 DioClient 回调触发)
|
||||
void forceLogout() {
|
||||
_clearAuthState();
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
/// 刷新用户信息
|
||||
Future<void> refreshUserInfo() async {
|
||||
if (!_isLoggedIn) return;
|
||||
|
||||
Reference in New Issue
Block a user