You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

63 lines
1.9 KiB

2 weeks ago
import 'package:get/get.dart';
import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart'; // 导入 debugPrint
import 'package:get_storage/get_storage.dart';
import 'package:problem_check_system/data/providers/local_database.dart';
class InitialBinding implements Bindings {
@override
void dependencies() {
// 全局注册 GetStorage 实例 - 也改为使用 put 确保立即创建
Get.put<GetStorage>(GetStorage(), permanent: true);
// 全局注册 Dio 实例 - 使用 put 而不是 lazyPut,并设置为永久
Get.put<Dio>(createDioInstance());
//
Get.put<LocalDatabase>(LocalDatabase());
}
// 提取创建 Dio 实例的逻辑到单独的方法
Dio createDioInstance() {
final dio = Dio(
BaseOptions(
baseUrl: 'https://xhdev.anxincloud.cn', // 替换为你的服务器地址
connectTimeout: const Duration(seconds: 15),
receiveTimeout: const Duration(seconds: 15),
),
);
// 添加日志拦截器,仅在调试模式下打印日志
if (kDebugMode) {
dio.interceptors.add(
LogInterceptor(
requestBody: true,
responseBody: true,
logPrint: (o) => debugPrint(o.toString()),
),
);
}
// 添加认证拦截器
dio.interceptors.add(
InterceptorsWrapper(
onRequest: (options, handler) {
final token = ""; //todo 获取token
if (token != null && token.isNotEmpty) {
options.headers['Authorization'] = 'Bearer $token';
}
return handler.next(options);
},
onError: (DioException e, handler) {
if (e.response?.statusCode == 401) {
// 如果收到 401 Unauthorized 错误,跳转回登录页
Get.offAllNamed('/login');
}
return handler.next(e);
},
),
);
return dio;
}
}