创建HTTP_CONFIG文件
/lib/utils/http/http_config.dart
此文件用来设置BaseOptions dio的公共配置文件!
1 2 3 4 5
| class HTTPConfig { static const baseURL = "http://5d85ccfb1e61af001471bf60.mockapi.io"; static const timeout = 60 * 1000; }
|
baseURL: api 接口地址! 例如: http://5d85ccfb1e61af001471bf60.mockapi.io/user
timeout: 超时时间! 响应超时, 请求超时等...
创建HTTP核心文件
/lib/utils/http/http.dart
此文件用来初始化dio实例, 并配置request请求方法,以及interceptor拦截器相关配置!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
| import 'package:dio/dio.dart'; import 'package:flutter_easyloading/flutter_easyloading.dart'; import 'package:rent_house/utils/http/interceptor.dart'; import './http_config.dart';
class HTTPRequest { static final BaseOptions options = BaseOptions( baseUrl: HTTPConfig.baseURL, connectTimeout: const Duration(milliseconds: HTTPConfig.timeout), receiveTimeout: const Duration(milliseconds: HTTPConfig.timeout));
static Dio dio = Dio(options);
static Future request( String url, { String method = "get", data, Map<String, dynamic>? params, Options? customOptions, ProgressCallback? onSendProgress, ProgressCallback? onReceiveProgress, }) async { Options options = customOptions ?? Options(method: method);
List<Interceptor> inters = [];
inters.add(AuthInterCeptor());
statusCode: 200
access-control-allow-headers: X-Requested-With
access-control-allow-origin: * date: Sun, 09 Apr 2023 06:30:44 GMT
content-encoding: gzip
strict-transport-security: max-age=31536000
server: Tengine
*/ inters.add(LogInterceptor(responseHeader: false, responseBody: true));
dio.interceptors.addAll(inters); try { Response response = await dio.request(url, data: data, queryParameters: params, options: options, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress); return response.data; } on DioException catch (e) { print('戳错了?????????? ${e.toString()}'); EasyLoading.showError(e.toString(), duration: const Duration(milliseconds: 1500), maskType: EasyLoadingMaskType.black); return Future.error(e); } } }
|
创建自定义拦截器
/lib/utils/http/interceptor.dart
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
| import 'package:flutter_easyloading/flutter_easyloading.dart'; import 'package:get/get_core/get_core.dart'; import 'package:get/get_navigation/src/extension_navigation.dart';
import 'package:dio/dio.dart';
import '../../router/app_pages.dart';
class AuthInterCeptor extends Interceptor { AuthInterCeptor();
@override void onRequest(RequestOptions options, RequestInterceptorHandler handler) { final listPath = ["/login", "/resgiter", "/sendMsgCode", "/api/qq/vip"]; if (listPath.contains(options.path)) { print("/api/qq/vip"); return handler.next(options); }
String access_token = "access_token"; options.headers.addAll({'Authorization': access_token}); return handler.next(options); }
@override void onResponse(Response response, ResponseInterceptorHandler handler) { if (response.statusCode == 401) { EasyLoading.showToast( 'token is invalid or expired! Please try again later!', duration: const Duration(seconds: 3));
Get.toNamed(Routes.LOGIN); } super.onResponse(response, handler); }
@override void onError(DioException err, ErrorInterceptorHandler handler) { EasyLoading.showError(err.message as String); super.onError(err, handler); } }
|
api模块封装
新建/lib/api/user.dart模块
1 2 3 4 5 6 7 8 9 10 11
| import '../../utils/http/http.dart';
class UserAPI { static Future getUserList({Map<String, dynamic>? params}) { return HTTPRequest.request('/user');
} }
|
场景应用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| Future<List<String>> Function(String filter) asyncItems = (String filter) async { try { var userList = await UserAPI.getUserList(params: {"filter": filter});
List<UserModel>? models = UserModel.fromJsonList(userList);
List<String> UserNameList = models!.map((e) => e.name).toList(); return UserNameList; } catch (e) { print('报错了~~~~ $e'); return []; } };
|