初始化

This commit is contained in:
zhu
2026-03-10 13:36:40 +08:00
commit b03e64957c
111 changed files with 4536 additions and 0 deletions

View File

@@ -0,0 +1,65 @@
import 'package:app/data/models/api_dto.dart';
import 'package:app/data/repository/auto_repo.dart';
import 'package:dio/dio.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import '../event/event_bus.dart';
import '../event/global_event.dart';
///请求拦截器
void onRequest(RequestOptions options, RequestInterceptorHandler handler) async {
String? token = await AuthRepo.getToken();
options.headers['Authorization'] = 'Bearer $token';
return handler.next(options);
}
///响应拦截器
void onResponse(Response<dynamic> response, ResponseInterceptorHandler handler) async {
var apiResponse = ApiDto.fromJson(response.data);
if (apiResponse.code == 1) {
response.data = apiResponse.data;
handler.next(response);
} else if (apiResponse.code == 401) {
final bus = EventBus();
bus.publish(UnauthorizedEvent());
handler.next(response);
} else {
handler.reject(
DioException(
requestOptions: response.requestOptions,
response: response,
error: {'code': apiResponse.code, 'message': apiResponse.message},
),
);
showError(apiResponse.message);
}
}
///错误响应
void onError(DioException e, ErrorInterceptorHandler handler) async {
var title = "";
if (e.type == DioExceptionType.connectionTimeout) {
title = "请求超时";
} else if (e.type == DioExceptionType.badResponse) {
if (e.response?.statusCode == 401) {
final bus = EventBus();
bus.publish(UnauthorizedEvent());
title = "登录信息已失效,请重新登录";
} else if (e.response?.statusCode == 404) {
title = "接口404不存在";
} else {
title = "500";
}
} else if (e.type == DioExceptionType.connectionError) {
title = "网络连接失败";
} else {
title = "异常其他错误";
}
showError(title);
handler.next(e);
}
///显示错误信息
void showError(String message) {
EasyLoading.showError(message);
}

View File

@@ -0,0 +1,43 @@
import 'package:dio/dio.dart';
import '../config/global.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;
}
}