In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)05/31 Report--
This article mainly introduces "how to achieve the secondary encapsulation of the network framework dio in Flutter". In the daily operation, I believe that many people have doubts about how to realize the secondary encapsulation of the network framework dio in Flutter. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts of "how to achieve the secondary encapsulation of the network framework dio in Flutter". Next, please follow the editor to study!
In fact, the dio framework has been encapsulated very well, but in the actual combat project, in order to manage the project uniformly, it is still necessary to re-package the dio framework.
Overall idea: in general, the data returned by the background can be divided into two parts, 1, status data, 2, rendering data. Status data is whether the interface returns data related to the data normally. This data has nothing to do with the business. We can encapsulate it and manage it. Rendering data is the data we need to render the page. This data needs to be processed by ourselves.
Next, we will mainly deal with the content of the rendering data. I defined two functions. The rendering data may be an object or an array. I processed them separately and defined two functions to accept the rendering data.
/ / define two functions typedef Success = Function (T data); request data data is obj object typedef SuccessList = Function (List data); / / request data data is [] array
/ / response header data unified management class BaseRes {int? Code;// status code String? Message; / / status code description T? Data; / / render data BaseRes ({this.code, this.message, this.data}); factory BaseRes.fromJson (json) {/ / json render json data try {if (json ["code"]! = null) {try {code = json ["code"];} catch (e) {code =-1 }} else {return BaseRes (code:-1, message: "Server deserted ~", data: null);} return BaseRes (code: json ["code"]?-1, message: json ["message"], data: BeanFactory.generateOBJ (json ["data"])) } catch (e) {return BaseRes (code:-1, message: "Server deserted ~", data: null);}
Returns the array example omitted. Just change T?data to List data, more or less the same.
Render entity class conversion:
/ / entity bean conversion factory class class BeanFactory {static T? GenerateOBJ (json) {/ / T.toString () class name try {switch (T.toString ()) {case "int": return json; case "bool": return json; case "String": return json; default: / / entity class serialization return TestBean.formJson (json) as T }} catch (e) {return null;}
Entity class:
/ / Test beanclass TestBean {String? Msg; bool? IsSelector; TestBean (this.msg,this.isSelector); TestBean.fromJson (dynamic json) {msg = json ["msg"]; isSelector = json ["isSelector"];} Map toJson () {var map = {}; map ["msg"] = msg; map ["isSelector"] = isSelector; return map;}}
The JsonToDart plug-in used in the actual project can be generated with one click. The only downside of this plug-in is that it cannot be serialized in the generated file, and everything else is fine.
Next, we need to re-encapsulate the dio request. The core request method of the dio library is the request method. The get and post methods of dio are all based on the request method, so we have to encapsulate the request method into what we need again.
/ / dio configuration class class DioManager {static const baseUrl = "https://xxx"; / / formal environment static DioManager instance = DioManager._internal (); Dio? _ dio; final Map _ headers = {} / / initialize the singleton privatization structure dio DioManager._internal () {if (_ dio = = null) {BaseOptions options = BaseOptions (baseUrl: baseUrl, contentType: Headers.jsonContentType, responseType: ResponseType.json, receiveDataWhenStatusError: false, connectTimeout: _ connectTimeout, receiveTimeout: _ receiveTimeout, headers: _ headers); _ dio = Dio (options) / / formal environment interception log printing if (! const bool.fromEnvironment ("dart.vm.product")) {_ dio?.interceptors .add (LogInterceptor (requestBody: true, responseBody: true));} Future imageToBytes (String imageUrl) async {var response = await _ dio?.get (imageUrl, options: Options (responseType: ResponseType.bytes)); return Uint8List.fromList (response?.data);} get header = > _ headers / Update headerupdateHeader () {_ dio?.options.headers = _ headers;} / request, returned rendering data T _ method / method: request method, NWMethod.GET, etc. / path: request address / params: request parameters / success: request success callback / error: request failure callback Future request (Method method, String path, {String? BaseUrl, Map? Params, data, ProgressCallback? OnSendProgress, / / upload data progress ProgressCallback? OnReceiveProgress, / / accept data progress Success? Success, Function (ErrorRes)? Error}) async {try {var connectivityResult = await (Connectivity (). CheckConnectivity ()); if (connectivityResult = = ConnectivityResult.none) {if (error! = null) {error (ErrorRes (code:-9, message: "Network exception ~, please check your network status!");} return;} _ setBaseUrl (baseUrl); / / dynamically set baseUrl Response? Response = await _ dio?.request (path, queryParameters: params, data: data, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, options: Options (method: methodValues [method])); if (response! = null) {BaseRes entity = BaseRes.fromJson (response.data) / / object data structure if (entity.code = 200 & & entity.data! = null) {if (success! = null) success (entity.data);} else {if (error! = null) {error (code: entity.code, message: entity.message)) } else {if (error! = null) error (ErrorRes (code:-1, message: "unknown error");}} on DioError catch (e) {if (error! = null) error (createErrorEntity (e));}}
Http finally invokes the class:
Typedef Success = Function (T data); / / define a function request successful callback typedef Error = Function (ErrorRes errorRes); / / request failed unified callback typedef SuccessList = Function (List data); / / request data data is [] collection / generic call API class class Http {/ / private construction Http._internal (); static Http instance = Http._internal () / get request / baseUrl switch baseUrl / params parameters / / success request object successful callback / successList request list successful callback / error error callback / [isList] whether the requested data is the List list default object / [isList] = true request data data is [] list list void get (String url, {String? BaseUrl, Map? Params, Success? Success, SuccessList? SuccessList, Error? Error, bool isList = false}) {if (isList) {_ requestList (Method.get, url, baseUrl: baseUrl, params: params, success: successList, error: error);} else {_ request (Method.get, url, baseUrl: baseUrl, params: params, success: success, error: error) }} / / post request / baseUrl switch baseUrl/// params parameters / data upload form data formData/// success request object callback successfully / successList request list successful callback / error error callback / [isList] whether the requested data is the List list default object / [isList] = true request data data is [] list list void post (String url, {String? BaseUrl, Map? Params, required data, Success? Success, SuccessList? SuccessList, Error? Error, bool isList = false}) {if (isList) {_ requestList (Method.post, url, data: data, baseUrl: baseUrl, params: params, success: successList, error: error);} else {_ request (Method.post, url, data: data, baseUrl: baseUrl, params: params, success: success, error: error);}}
Call the actual combat application:
I have added a layer of model processing to the business module, and the page only needs to be mixed with our model layer to call the specific method.
Mixin LoginModel {/ / get requests loadCode (String value, {required Success success, required Error error,}) {Http.instance.get (Api.loadxxx, params: {"key": value}, success: success, error: error);}} at this point, the study on "how to implement the secondary encapsulation of dio in Flutter" is over, hoping to solve everyone's doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.