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
77
// Dio 网络请求工具类
import 'dart:convert';
import 'package:clx_flutter_message/clx_flutter_message.dart';
// ignore: depend_on_referenced_packages
import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
class Api {
static final dio = messageConfig.dio;
// 构建网络请求同步请求
Future<dynamic> requestSync({
required String requestUrl,
required Method method,
Map<String, dynamic>? queryParameters,
Object? data,
}) async {
try {
var response = await dio?.request(
requestUrl,
queryParameters: queryParameters,
data: data,
options: _checkOptions(method.value),
);
try {
var data = response?.data;
if (data is Map) {
return data;
} else if (data is String) {
return _jsonDecode(data);
}
return data;
} catch (e) {
debugPrint("数据解析错误:${e.toString()}");
return {"code": 400, "message": "数据解析错误"};
}
} on DioException catch (e) {
if (e.response != null) {
debugPrint(
"请求错误:${e.response!.statusCode} ${e.response!.requestOptions.path}");
} else {
// Something happened in setting up or sending the request that triggered an Error
debugPrint("请求错误:${e.error}");
}
return {"code": 500, "message": "服务器请求错误"};
}
}
// Options
Options _checkOptions(String method) {
Options options = Options();
options.method = method;
return options;
}
// jsonDecode
Map<String, dynamic> _jsonDecode(String json) {
return jsonDecode(json);
}
}
enum Method {
get,
post,
put,
patch,
delete,
}
extension MethodExtension on Method {
String get value => ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'][index];
}