当前位置:网站首页>Actual combat of flutter - DIO of request encapsulation (II)
Actual combat of flutter - DIO of request encapsulation (II)
2022-07-29 04:27:00 【Blue faced scholar】

It took two years flutter, Have some experience , Not empty head and brain , Only for practical use , For study or use flutter My little friend's reference , Learning is still shallow , If there is anything wrong, we hope all gods will correct it , So as not to mislead others , Thank you here. ~( Originality is not easy. , Please indicate the source and author when forwarding )
Be careful : No special instructions ,flutter Version is 3.0+
The last one is a summary api Organizational structure of , In this article, we discuss Flutter Common request Library Dio The use and packaging of .
One .dio
commonly http We are requested to pay attention to the following points :
Access path , Request mode , Request header , Request parameters , Timeout time , Return results , Return type and so on .
notes :( Yes http/https The agreement is not very clear , Children's shoes that need make-up lessons can go to the basic tutorial https://www.runoob.com/http/http-tutorial.html)
Take a look first dio Configurable parameters :
BaseOptions({
String? method,
int? connectTimeout,
int? receiveTimeout,
int? sendTimeout,
String baseUrl = '',
Map<String, dynamic>? queryParameters,
Map<String, dynamic>? extra,
Map<String, dynamic>? headers,
ResponseType? responseType = ResponseType.json,
String? contentType,
ValidateStatus? validateStatus,
bool? receiveDataWhenStatusError,
bool? followRedirects,
int? maxRedirects,
RequestEncoder? requestEncoder,
ResponseDecoder? responseDecoder,
ListFormat? listFormat,
this.setRequestContentTypeWhenNoPayload = false,
})
In addition to the basic configuration dio Interceptors are also provided interceptors, Adapter httpClientAdapter, Request method get,post,delete,put,patch,download And other basic packaging , It's convenient for us to use .
Two .Http Foundation class
class Http {
/// Define various timeout times
static const int CONNECT_TIMEOUT = 10000; // default setting 10s Overtime
static const int RECEIVE_TIMEOUT = 3000;
static const int SEND_TIMEOUT = 3000;
Dio? dio;
static Http _instance = Http._internal();
1._internal() obtain Dio Example method , It is mainly about configuring adapters
Http._internal() {
dio = Dio();dio.httpClientAdapter = DefaultHttpClientAdapter()
..onHttpClientCreate = (HttpClient c,lient) {
client.idleTimeout = Duration(milliseconds: CONNECT_TIMEOUT);
};// Add an error unified processing interceptor
dio!.interceptors.add(ErrorInterceptor());// Add log interceptor
dio!.interceptors.add(DioLogInterceptor());
2.post Method source code example
Future post(
String path, {
required String baseUrl,
Map<String, dynamic>? params,
Map<String, dynamic>? headers,
data,
Options? options,
CancelToken? cancelToken,
}) async {
Options requestOptions = options ?? Options();
//requestOptions.baseUrl = baseUrl;
Map<String, dynamic>? _authorization = headers ?? getAuthorizationHeader();
if (_authorization != null) {
requestOptions = requestOptions.copyWith(headers: _authorization);
}
dio!.options.baseUrl = baseUrl;
dio!.options.connectTimeout = CONNECT_TIMEOUT;
dio!.options.receiveTimeout = RECEIVE_TIMEOUT;
dio!.options.sendTimeout = SEND_TIMEOUT;
var response;
var timeout = Duration(milliseconds: dio!.options.connectTimeout);
cancelToken = CancelToken();
var t = Timer(timeout, () {
if (response == null) {
cancelToken!.cancel();
}
});
response =
await dio!.post(path, data: data, queryParameters: params, options: requestOptions, cancelToken: cancelToken);
t.cancel();
return response.data;
}
cancelToken yes dio Provide a very useful thing , You can take the initiative to return when it times out , Actively end the request , And trigger DioErrorType.cancel The wrong event of .
3、 ... and .httpUtils Strengthen packaging
1. Add whether to wait for processing
Also with post For example , We define a method call http The base class
static Future post(String path,{data,required String baseUrl,
Map<String, dynamic>? params,
Options? options,
CancelToken? cancelToken,
bool showLoading = false}
Here we add a parameter showLoading, In our actual development process , There are some operations to block user operations , Wait for interface request , Some are requests that do not require user awareness , We can be in all api in , This parameter is added by default as false, It is necessary to set this parameter to true, Here's an example :
/// Forget the password
static Future<String> forgetPassword(dynamic param, { bool showLoading= false}) async {
var res = await HttpUtils.post(_forgetPassword, data: param, baseUrl: "xxx" showLoading: showLoading);
return res;
}
When judgment requires loading When
if (showLoading) {
showLoadingDialog();
}
The author uses flutter_smart_dialog: ^4.5.3+7, It's easy to use , You can encapsulate what you need loading style .
2. Define unified return types
class ApiResponse<T> implements Exception {
String? errorMsg;
String? msg;
int? code;
T? data;
ApiResponse(this.msg);
ApiResponse.error(String msg) {
toastMsg(msg);
}
@override
String toString() {
return "Msg : $msg \n errorMsg : $errorMsg \n Data : $data";
}
ApiResponse.fromJson(Map<String, dynamic> json) {
msg = json['msg'];
errorMsg = json['errorMsg'];
code = json['code'];
data = json['data'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['msg'] = this.msg;
data['errorMsg'] = this.errorMsg;
data['code'] = this.code;
data['data'] = this.data;
return data;
}
}
3. Return processing
Judge whether the background return is correct code, Returns the result , Clear after completion loading state .
Source code is as follows
class HttpUtils {
static Future post(String path,
{data,
required String baseUrl,
Map<String, dynamic>? params,
Options? options,
CancelToken? cancelToken,
bool showLoading = false,
bool canNull = false,
Function(Object?)? onError,
bool errorToast = true,
bool isolate = true}) async {
if (showLoading) {
showLoadingDialog(path: path);
}
return Http()
.post(
path,
baseUrl: baseUrl,
data: data,
params: params,
options: options,
cancelToken: cancelToken,
)
.then((value) {
var result = ApiResponse.fromJson(value is Map ? value : jsonDecode(value));
if (result.code == 2000) {
return result.data;
} else {
throw ApiResponse(result.msg!);
}
}).onError((error, stackTrace) {
if (onError != null) {
onError(error);
}
if (error is RemoteError) {
toastMsg(" Network connection failed ", displayType: SmartToastType.last);
} else if (error is ApiResponse) {
toastMsg(error.msg!);
} else {
toastMsg(" Unknown error ");
}
throw Exception(error.toString());
}). whenComplete(() {
if (showLoading) {
SmartDialog.dismiss();
}
});}
边栏推荐
- Redux quick start
- 11.备份交换机
- Two forms of softmax cross entropy + numpy implementation
- Common components of solder pad (2021.4.6)
- Niuke IOI weekly 27 popularity group
- Fuzzy query of SQL
- The function "postgis_version" cannot be found when installing PostGIS
- Implementation of jump connection of RESNET (pytorch)
- Labelme cannot open the picture
- Not for 60 days, magical dictionary
猜你喜欢

Update learning materials daily

12.优先级队列和惰性队列

No, just stick to it for 64 days. Find the insertion location

Hengxing Ketong invites you to the 24th China expressway informatization conference and technical product exhibition in Hunan

MySQL - deep parsing of MySQL index data structure

Definition and implementation of stack and queue (detailed)

顺序表和链表

信号处理中的反傅里叶变换(IFFT)原理

9.延迟队列

Don't stick to it for 68 days. Baboons eat bananas
随机推荐
Machine vision Series 2: vs DLL debugging
String, array, generalized table (detailed)
Not for 61 days. The shortest word code
Leetcode 686. KMP method of repeatedly superimposing strings (implemented in C language)
Compilation and linking
Shielding ODBC load balancing mode in gbase 8A special scenarios?
Record of problems encountered in ROS learning
Integration of Nan causes in pytorch training model
顺序表和链表
Won't you just stick to 69 days? Merge range
Don't stick to it for 68 days. Baboons eat bananas
不会就坚持65天吧 只出现一次的数字
Realize the effect of univariate quadratic equation through JS. Enter the coefficients of a, B and C to calculate the values of X1 and x2
6. Pytest generates an allure Report
Post export data, return
Log configuration logback
Definition and implementation of stack and queue (detailed)
Why are there so many unknowns when opengauss starts?
visio画网格
15.federation