Files
flutterApp/lib/core/network/dio_client.dart
2026-03-16 12:40:02 +08:00

59 lines
1.7 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:dio/dio.dart';
import 'package:maibu_satabot_v2/core/consts/http_api_consts.dart';
import 'package:maibu_satabot_v2/core/app/app_user_cubit.dart';
import 'package:maibu_satabot_v2/core/di/injection.dart';
import 'package:maibu_satabot_v2/features/auth/presentation/bloc/auth_cubit.dart';
class DioClient {
static Dio create() {
final dio = Dio(
BaseOptions(
baseUrl: HttpApiConsts.baseUrl,
connectTimeout: const Duration(seconds: 20),
receiveTimeout: const Duration(seconds: 20),
headers: {'Content-Type': 'application/json'},
),
);
dio.interceptors.add(LogInterceptor(requestBody: true, responseBody: true));
dio.interceptors.add(
InterceptorsWrapper(
onRequest: (options, handler) {
final userCubit = sl<AppUserCubit>();
final token = userCubit.state.user?.token;
if (token != null && token.isNotEmpty) {
options.headers['Authorization'] = 'Bearer $token';
}
return handler.next(options);
},
// ======================
// ✅ 关键:401 自动拦截
// ======================
onResponse: (response, handler) {
return handler.next(response);
},
onError: (DioException e, handler) async {
// 401 = token 过期 / 未授权
if (e.response?.statusCode == 401) {
try {
// 调用 logout 清除本地缓存 + 跳登录
await sl<AuthCubit>().logout();
} catch (ex) {
// 防止报错
}
}
return handler.next(e);
},
),
);
return dio;
}
}