From a0229e653e0b1da285e98d1457fc94604c228456 Mon Sep 17 00:00:00 2001 From: hailin Date: Sun, 11 Jan 2026 18:00:33 -0800 Subject: [PATCH] =?UTF-8?q?fix(mining-app):=20=E4=BF=AE=E5=A4=8D=E7=99=BB?= =?UTF-8?q?=E5=BD=95=E5=90=8EAPI=E8=AF=B7=E6=B1=82token=E6=9C=AA=E6=9B=B4?= =?UTF-8?q?=E6=96=B0=E7=9A=84=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 问题原因: ApiClient使用内存缓存的token,登录后虽然保存到SharedPreferences, 但ApiClient的内存缓存未更新,导致后续请求仍使用旧token或无token。 解决方案: 移除内存缓存,每次请求都从SharedPreferences读取最新token, 确保登录后立即生效。 Co-Authored-By: Claude Opus 4.5 --- .../lib/core/network/api_client.dart | 21 +++++-------------- 1 file changed, 5 insertions(+), 16 deletions(-) diff --git a/frontend/mining-app/lib/core/network/api_client.dart b/frontend/mining-app/lib/core/network/api_client.dart index 3508734b..8d3bcee0 100644 --- a/frontend/mining-app/lib/core/network/api_client.dart +++ b/frontend/mining-app/lib/core/network/api_client.dart @@ -5,7 +5,6 @@ import '../error/exceptions.dart'; class ApiClient { final Dio dio; - String? _accessToken; ApiClient({required this.dio}) { dio.options = BaseOptions( @@ -21,27 +20,17 @@ class ApiClient { // 添加请求拦截器,自动注入 token dio.interceptors.add(InterceptorsWrapper( onRequest: (options, handler) async { - if (_accessToken == null) { - // 从存储中加载 token - final prefs = await SharedPreferences.getInstance(); - _accessToken = prefs.getString('access_token'); - } - if (_accessToken != null) { - options.headers['Authorization'] = 'Bearer $_accessToken'; + // 每次请求都从存储中读取最新的 token,确保登录后立即生效 + final prefs = await SharedPreferences.getInstance(); + final token = prefs.getString('access_token'); + if (token != null && token.isNotEmpty) { + options.headers['Authorization'] = 'Bearer $token'; } handler.next(options); }, )); } - void setAccessToken(String? token) { - _accessToken = token; - } - - void clearAccessToken() { - _accessToken = null; - } - Future get( String path, { Map? queryParameters,