| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980 |
- import 'package:dio/dio.dart';
- import 'package:flutter/material.dart';
- import 'package:fun_selfie_app/dio_util/dio_interceptors.dart';
- // import 'package:fun_selfie_app/dio_util/dio_method.dart';
- class DioUtil {
- static DioUtil? _instance;
- static Dio _dio = Dio();
- Dio get dio => _dio;
- DioUtil._internal() {
- _instance = this;
- _instance!._init();
- }
- factory DioUtil() => _instance ?? DioUtil._internal();
- static DioUtil? getInstance() {
- _instance ?? DioUtil._internal();
- return _instance;
- }
- /// 取消请求token
- final CancelToken _cancelToken = CancelToken();
- ///
- _init() {
- /// 初始化基本选项
- BaseOptions options = BaseOptions(
- baseUrl:
- "http://118.123.247.197:8080/jeecg-boot/", //"http://localhost:8080",
- connectTimeout: const Duration(seconds: 6), // 连接超时时间
- receiveTimeout: const Duration(seconds: 6)); // 响应超时时间
- /// 初始化dio
- _dio = Dio(options);
- /// 添加拦截器
- _dio.interceptors.add(DioInterceptors());
- }
- /// 开启日志打印
- void openLog() {
- _dio.interceptors.add(LogInterceptor(responseBody: true));
- }
- /// 请求类
- Future<T> request<T>(
- String path, {
- String method = 'get',
- Map<String, dynamic>? params,
- data,
- CancelToken? cancelToken,
- Options? options,
- ProgressCallback? onSendProgress,
- ProgressCallback? onReceiveProgress,
- }) async {
- options ??= Options(method: method);
- try {
- Response response;
- response = await _dio.request(path,
- data: data,
- queryParameters: params,
- cancelToken: cancelToken ?? _cancelToken,
- options: options,
- onSendProgress: onSendProgress,
- onReceiveProgress: onReceiveProgress);
- return response.data;
- } on DioException catch (e) {
- debugPrint(e.toString());
- rethrow;
- }
- }
- /// 取消网络请求
- void cancelRequests({CancelToken? token}) {
- token ?? _cancelToken.cancel("cancelled");
- }
- }
|