network_manager.dart.txt
2.06 KB
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
import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:wow_english/models/response_model.dart';
import 'package:wow_english/network/basic_configuration.dart.txt';
enum HttpMethod {
get,
put,
post,
head,
patch,
delete,
}
class DioUtil {
static final Dio _dio = getDefDio();
static Dio getDefDio() {
Dio dio = Dio();
dio.options = getDefOptions();
return dio;
}
static BaseOptions getDefOptions() {
final BaseOptions options = BaseOptions();
options.baseUrl = BasicConfigurationManager().baseUrl ?? '';
options.connectTimeout = const Duration(milliseconds: 1000);
options.receiveTimeout = const Duration(milliseconds: 1000);
return options;
}
Future<void> requestData<T>(
HttpMethod method,
String path, {
data,
Function? successCallBack,
Function? errorCallBack,
Map<String, dynamic>? queryParameters,
ProgressCallback? onSendProgress,
ProgressCallback? onReceiveProgress,
}) async {
try {
Map<String, dynamic> headers = <String, dynamic>{};
if (method == HttpMethod.post) {
headers['content-type'] = 'application/json';
}
Response<dynamic> response;
response = await _dio.request(path,
data: data ?? {},
queryParameters: queryParameters,
options: Options(method: method.name, headers: headers),
onSendProgress: onSendProgress,
onReceiveProgress: onReceiveProgress);
int statusCode = response.statusCode ?? 0;
if (statusCode >= 200 && statusCode < 300) {
if (kDebugMode) {
print(response.data);
}
final ResponseModel model = ResponseModel.fromJson(response.data);
if (model.code == 200) {
successCallBack?.call(response.data);
} else {
errorCallBack?.call(model.msg);
}
} else {
errorCallBack?.call('请求失败');
}
} on DioException catch (error) {
if (kDebugMode) {
print(error);
}
errorCallBack?.call("网络错误: ${error.message}");
}
}
}