初始化

This commit is contained in:
zhutao
2025-11-19 17:56:39 +08:00
commit 1b28239352
115 changed files with 5440 additions and 0 deletions

View File

@@ -0,0 +1,20 @@
class ApiDto<T> {
final int code;
final String message;
final T data;
ApiDto({
required this.code,
required this.message,
required this.data
});
factory ApiDto.fromJson(Map<String, dynamic> json) {
return ApiDto<T>(
code: json['code'],
message: json['message'],
data: json['data'],
);
}
}

View File

@@ -0,0 +1,51 @@
import 'package:dio/dio.dart';
import '../dto/base_dto.dart';
///请求拦截器
void onRequest(
RequestOptions options,
RequestInterceptorHandler handler,
) {
return handler.next(options);
}
///响应拦截器
void onResponse(
Response<dynamic> response,
ResponseInterceptorHandler handler,
) {
var apiResponse = ApiDto.fromJson(response.data);
if (apiResponse.code == 1) {
handler.next(response);
} else {
handler.reject(
DioException(
requestOptions: response.requestOptions,
response: response,
error: {'code': 0, 'message': apiResponse.message},
),
);
}
}
///错误响应
void onError(
DioException e,
ErrorInterceptorHandler handler,
) {
if (e.type == DioExceptionType.connectionTimeout) {
print("请求超时");
} else if (e.type == DioExceptionType.badResponse) {
if (e.response?.statusCode == 404) {
print("接口404不存在");
} else {
print("500");
}
} else if (e.type == DioExceptionType.connectionError) {
print("网络连接失败");
} else {
print("接口请求异常报错");
}
}

View File

@@ -0,0 +1,43 @@
import 'package:dio/dio.dart';
import 'package:app/config/config.dart';
import 'interceptor.dart';
class Request {
static Dio _dio = Dio();
//返回单例
factory Request() {
return Request._instance();
}
//初始化
Request._instance() {
//创建基本配置
final BaseOptions options = BaseOptions(
baseUrl: Config.baseUrl(),
connectTimeout: const Duration(seconds: 10),
receiveTimeout: const Duration(seconds: 10),
);
_dio = Dio(options);
_dio.interceptors.add(InterceptorsWrapper(
onRequest: onRequest,
onResponse: onResponse,
onError: onError,
));
}
///get请求
Future<T> get<T>(String path, [Map<String, dynamic>? params]) async {
var res = await _dio.get(path, queryParameters: params);
return res.data;
}
///post请求
Future<T> post<T>(String path, Object? data) async {
var res = await _dio.post(path, data: data);
return res.data;
}
}