1。http_service.dart
import 'dart:convert'; import 'package:dio/dio.dart'; import 'package:carrynotenew/utils/logger.dart'; import 'package:carrynotenew/utils/network/error_response_handler.dart'; import 'package:carrynotenew/utils/network/retrofit_client.dart'; import 'package:carrynotenew/utils/bean/base_response_entity.dart'; import 'package:carrynotenew/utils/bean/chapter_info_entity.dart'; class HttpService { static late RetrofitClient _client; static void doInit() { var dio = Dio(); dio.interceptors.add(InterceptorsWrapper(onRequest: (options, handler) { options.headers["Content-Type"] = "application/x-www-form-urlencoded"; // options.headers["Accept-Language"] = Intr().currentLocale().languageCode; //设备信息【PC:PC网页端,MP:移动端,APP:原生APP】 //网站ID //机器型号 //系统版本号【APP强制使用】 // var commonParams = {"machineModel":Constants.model(),"siteId":"9000","siteType":"1","terminal":"APP","version":Constants.version()}; // options.queryParameters.addAll(commonParams); loggerArray([ "发起请求", "${options.baseUrl}${options.path}\n", "${options.method}\n", "${options.headers}\n", options.data ?? options.queryParameters ]); handler.next(options); }, onResponse: (response, handler) { loggerArray([ "返回响应", response.requestOptions.path, response.statusCode, "${response.statusMessage}\n", jsonEncode(response.data) ]); if (response.statusCode == 200) { handler.next(response); } else { ErrorResponseHandler().onErrorHandle( {"code": response.statusCode, "message": response.statusMessage}); } }, onError: (DioException e, handler) { loggerArray(["异常响应", e.toString()]); handler.next(e); })); _client = RetrofitClient(dio); } ///游戏返回体 ///封装请求体,自动处理各种异常问题 static Future<T> buildFuture<T>(RequestCallback callback, {bool loading = true, bool needMsg = false, bool errorHandler = true}) async { // if(loading){ EasyLoading.show(maskType: EasyLoadingMaskType.black,status: Intr().jiazaizhong); } try { var value = await callback.call(); // if(loading){ EasyLoading.dismiss(); } if (value.isOk()) { ///data为null时处理 return Future.value( value.data ?? (needMsg ? value.errorMsg.toString() : "")); } else { if (errorHandler) { ErrorResponseHandler().onErrorHandle( {"code": value.errorCode, "message": value.errorMsg.toString()}); } return Future.error(value.errorMsg.toString()); } } catch (error) { loggerArray(["请求异常信息", error]); // if(loading){ EasyLoading.dismiss(); } if (errorHandler) { ErrorResponseHandler().onErrorHandle(error); } return Future.error(error); } } static Future<String> doLogin( Map<String, dynamic> params, ) { return buildFuture<String>(() => _client.doLogin(params), loading: false); } static Future<List<ChapterInfoEntity>> getChapters() { return buildFuture<List<ChapterInfoEntity>>(() => _client.getChapters(), loading: false); } static Future<String> queryArticle( Map<String, dynamic> params, ) { return buildFuture<String>(() => _client.queryArticle(params), loading: false); } } typedef RequestCallback = Future<BaseResponseEntity<dynamic>> Function();
2.retrofit_client.dart
import 'package:dio/dio.dart' hide Headers; import 'package:retrofit/retrofit.dart'; import 'package:carrynotenew/utils/global.dart'; import 'package:carrynotenew/utils/bean/base_response_entity.dart'; import 'package:carrynotenew/utils/bean/chapter_info_entity.dart'; part 'retrofit_client.g.dart'; @RestApi(baseUrl: Global.base_url, parser: Parser.JsonSerializable) abstract class RetrofitClient { factory RetrofitClient(Dio dio, {String? baseUrl}) = _RetrofitClient; @GET('/wxarticle/chapters/json') Future<BaseResponseEntity<List<ChapterInfoEntity>>> getChapters(); @POST('/article/query/0/json') Future<BaseResponseEntity<String>> queryArticle( @Body() Map<String, dynamic> params, ); @POST('/login/doLogin') Future<BaseResponseEntity<String>> doLogin( @Body() Map<String, dynamic> params, ); }
3.生成请求实例 retrofit_client.g.dart
flutter pub run build_runner build
4.调用
HttpService.doLogin({ 'uname': _unameController.text, 'upass': _upassController.text }).then((value) => {debugPrint(value.toString())})
本文为看恩吧原创文章,转载无需和我联系,但请注明来自knsay.com