Flutter network requests Dio package library (single embodiment, the baseUrl dynamic, interceptor)

https://www.jianshu.com/p/5ead0cf96642

 

Several benefits package network requests:
1, to facilitate unified configuration request parameters, such as header, public parameter, encrypted rules
2, to facilitate debugging, print log
3, the code to optimize performance, to avoid abuse everywhere new object construct single global Example
4, simplify requesting step, exposing only the response data required in response to the error correction unified
5, the base class encapsulates the data interface, simplified analytical process
results example:


 
image.png

HttpManager definition

The overall configuration of a single embodiment, parameter configuration request, the generic configuration GET \ POST, support handover baseUrl

class HttpManager {
  static HttpManager _instance = HttpManager._internal(); Dio _dio; factory HttpManager() => _instance; ///通用全局单例,第一次使用时初始化 HttpManager._internal({String baseUrl}) { if (null == _dio) { _dio = new Dio(new BaseOptions( baseUrl: Address.BASE_URL_RELEASE, connectTimeout: 15000)); _dio.interceptors.add(new LogsInterceptors()); _dio.interceptors.add(new ResponseInterceptors()); } } static HttpManager getInstance({String baseUrl}) { if (baseUrl == null) { return _instance._normal(); } else { return _instance._baseUrl(baseUrl); } } //用于指定特定域名,比如cdn和kline首次的http请求 HttpManager _baseUrl(String baseUrl) { if (_dio != null) { _dio.options.baseUrl = baseUrl; } return this; } //一般请求,默认域名 HttpManager _normal() { if (_dio != null) { if (_dio.options.baseUrl != Address.BASE_URL_RELEASE) { _dio.options.baseUrl = Address.BASE_URL_RELEASE; } } return this; } ///通用的GET请求 get(url, params, {noTip = false}) async { Response response; try { response = await _dio.get(url, queryParameters: params); } on DioError catch (e) { return resultError(e); } if (response.data is DioError) { return resultError(response.data['code']); } return response.data; } ///通用的POST请求 post(url, params, {noTip = false}) async { Response response; try { response = await _dio.post(url, data: params); } on DioError catch (e) { return resultError(e); } if (response.data is DioError) { return resultError(response.data['code']); } return response.data; } } 

Log interceptor

The print request and return parameters

import 'package:dio/dio.dart';

class LogsInterceptors extends InterceptorsWrapper { 

In response interceptor

Filtered correct response data, preliminary data encapsulation

import 'package:dio/dio.dart';
import 'package:exchange_flutter/common/net/code.dart'; import 'package:flutter/material.dart'; import '../result_data.dart'; class ResponseInterceptors extends InterceptorsWrapper { @override onResponse(Response response) { RequestOptions option = response.request; try { if (option.contentType != null && option.contentType.primaryType == "text") { return new ResultData(response.data, true, Code.SUCCESS); } ///一般只需要处理200的情况,300、400、500保留错误信息 if (response.statusCode == 200 || response.statusCode == 201) { int code = response.data["code"]; if (code == 0) { return new ResultData(response.data, true, Code.SUCCESS, headers: response.headers); } else if (code == 100006 || code == 100007) { } else { Fluttertoast.showToast(msg: response.data["msg"]); return new ResultData(response.data, false, Code.SUCCESS, headers: response.headers); } } } catch (e) { print(e.toString() + option.path); return new ResultData(response.data, false, response.statusCode, headers: response.headers); } return new ResultData(response.data, false, response.statusCode, headers: response.headers); } } 

In response to the base class

IsSuccess default of 200 is true, the response is response.data, assigned to data

class ResultData {
  var data; bool isSuccess; int code; var headers; ResultData(this.data, this.isSuccess, this.code, {this.headers}); } 

Api package

Centralized management requests

class Api {
  ///示例请求
  static request(String param) { var params = DataHelper.getBaseMap(); params['param'] = param; return HttpManager.getInstance().get(Address.TEST_API, params); } } 

Public parameters and encryption

class DataHelper{
  static SplayTreeMap getBaseMap() { var map = new SplayTreeMap<String, dynamic>(); map["platform"] = AppConstants.PLATFORM; map["system"] = AppConstants.SYSTEM; map["channel"] = AppConstants.CHANNEL; map["time"] = new DateTime.now().millisecondsSinceEpoch.toString(); return map; } static string2MD5(String data) { var content = new Utf8Encoder().convert(data); var digest = md5.convert(content); return hex.encode(digest.bytes); } } 

Configuring address

Convenient address management

class Address {
  static const String TEST_API = "test_api"; } 

Example Request

dart json parsing of recommended json_serializable, some other pit, caution

void request() async { ResultData res = await Api.request("param"); if (res.isSuccess) { //拿到res.data就可以进行Json解析了,这里一般用来构造实体类 TestBean bean = TestBean.fromMap(res.data); }else{ //处理错误 } } 

Demo Institute Add  https://github.com/po1arbear/Flutter-Net.git



Author: Phantom Assassin
link: https: //www.jianshu.com/p/5ead0cf96642
Source: Jane books
are copyrighted by the author. Commercial reprint please contact the author authorized, non-commercial reprint please indicate the source.

Guess you like

Origin www.cnblogs.com/sundaysme/p/12624185.html