import 'package:dio/dio.dart'; import 'package:flutter_jdt_store/global.dart'; import 'package:flutter_jdt_store/utils/utils.dart'; import '../global.dart'; class Request { // 构造函数 Request() { init(); } static final Dio _dio = Dio(); static void init() { // 基本配置 _dio.options.baseUrl = Global.baseUrl; _dio.options.connectTimeout = const Duration(seconds: 10); _dio.options.receiveTimeout = const Duration(seconds: 10); _dio.options.headers["Content-Type"] = "application/json; charset=utf-8"; _dio.options.headers["token"] = StorageUtil().getString("token"); // 添加请求拦截器 _dio.interceptors.add(InterceptorsWrapper( onRequest: (options, handler) { // 在请求被发送之前做一些事情 return handler.next(options); // 必须返回 options }, )); // 添加响应拦截器 _dio.interceptors.add(InterceptorsWrapper( onResponse: (response, handler) { // 在响应被处理之前做一些事情 final Map data = response.data; // 状态码不等于200时抛出异常 if (data["code"] != 200) { ToolFn.tips(data["msg"].toString()); throw DioException( requestOptions: response.requestOptions, response: response, error: data["msg"], ); } return handler.next(response); // 必须返回 response }, onError: (DioException e, handler) { // 在响应错误被处理之前做一些事情 return handler.next(e); // 必须返回 error }, )); } static Future get(String path, {Map? params}) async { try { final Response response = await _dio.get(path, queryParameters: params); return response.data!; } catch (error) { throw _handleError(error); } } static Future post(String path, {Map? data}) async { try { final Response response = await _dio.post(path, data: data); return response.data!; } catch (error) { throw _handleError(error); } } // 处理错误 static Exception _handleError(error) { if (error is DioException) { String message = "网络请求失败"; if (error.response != null && error.response!.data != null) { message = error.response!.data.toString(); } return Exception(message); } else { return Exception("未知错误"); } } }