import 'package:dio/dio.dart';
|
import 'package:flutter/cupertino.dart';
|
import 'package:flutter/material.dart';
|
import 'package:get/get.dart';
|
import 'dart:convert';
|
import 'dart:async';
|
|
import '../pages/login/network_settings.dart';
|
|
class DioConfig {
|
static String baseURL = 'http://192.168.4.61:8085/xcjgwms'; //域名
|
static const timeout = 20000; //超时时间
|
|
// 更新 baseURL 中的 IP 地址
|
static Future<void> updateBaseURL() async {
|
final settings = await SettingService.getNetworkSettings();
|
String? ip = settings['ip'];
|
String? port = settings['port'].toString();
|
String? url = settings['url'];
|
|
if (ip != null && ip.isNotEmpty) {
|
baseURL = 'http://$ip:$port/$url'; // 动态更新 baseURL
|
DioRequest dioRequest = DioRequest.getInstance();
|
dioRequest.updateBaseUrl(baseURL);
|
}
|
}
|
}
|
|
class DioRequest {
|
late Dio dio;
|
static DioRequest? _instance;
|
|
/// 构造函数
|
DioRequest._internal() {
|
dio = Dio();
|
dio.options = BaseOptions(
|
baseUrl: DioConfig.baseURL,
|
connectTimeout: Duration(milliseconds: DioConfig.timeout),
|
sendTimeout: Duration(milliseconds: DioConfig.timeout),
|
receiveTimeout: Duration(milliseconds: DioConfig.timeout),
|
contentType: 'application/json; charset=utf-8',
|
headers: {});
|
/// 请求拦截器 and 响应拦截机 and 错误处理
|
dio.interceptors.add(InterceptorsWrapper(onRequest: (options, handler) {
|
print("\n================== 请求数据 ==========================");
|
print("url = ${options.uri.toString()}");
|
print("headers = ${options.headers}");
|
print("data = ${options.data}");
|
return handler.next(options);
|
}, onResponse: (response, handler) {
|
print("\n================== 响应数据 ==========================");
|
print("statusCode = ${response.statusCode}");
|
print("data = ${response.data}");
|
print("data = ${response.data['code']}");
|
print("\n");
|
if (response.data['code'] == 403) {
|
Get.snackbar('Error', 'Access denied. Please login again.');
|
Future.delayed(Duration(seconds: 2), () {
|
Get.offNamed('/login');
|
},);
|
}
|
handler.next(response);
|
}, onError: (DioError e, handler) {
|
print("\n================== 错误响应数据 ======================");
|
print("type = ${e.type}");
|
print("message = ${e.message}");
|
print("\n");
|
Get.snackbar('响应错误', '请检查网络连接或联系管理员');
|
return handler.next(e);
|
}));
|
}
|
// 获取单例实例
|
static DioRequest getInstance() {
|
return _instance ??= DioRequest._internal();
|
}
|
// 动态设置新的 baseURL(IP 地址)
|
void updateBaseUrl(String newBaseUrl) {
|
dio.options.baseUrl = newBaseUrl;
|
}
|
|
}
|