Flutter之Dio封装+实例(自己梳理)
warning:
这篇文章距离上次修改已过190天,其中的内容可能已经有所变动。
import 'package:dio/dio.dart';
class HttpUtils {
static const String baseUrl = "http://www.phonegap100.com/";
static Dio dio = new Dio();
// 获取
static Future<Response> get(String path, {
Map<String, dynamic> params,
Options options,
}) async {
Response response;
try {
response = await dio.get(baseUrl + path, queryParameters: params, options: options);
} catch (e) {
print(e);
}
return response;
}
// 提交
static Future<Response> post(String path, {
Map<String, dynamic> data,
Options options,
}) async {
Response response;
try {
response = await dio.post(baseUrl + path, data: data, options: options);
} catch (e) {
print(e);
}
return response;
}
}
// 使用示例
void main() async {
Response response;
// 发起GET请求
response = await HttpUtils.get('api/home/categories.php');
print(response.data);
// 发起POST请求
response = await HttpUtils.post('api/home/categories.php', data: {
"name": "John Doe",
"age": 30
});
print(response.data);
}
这个示例代码展示了如何封装一个简单的Dio HTTP请求工具类,并提供了两个静态方法get
和post
来处理HTTP GET和POST请求。同时,它还展示了如何在主函数中使用这个封装好的工具类来发起请求并打印响应数据。这个例子简洁明了,并且使用了try-catch来处理可能发生的异常,增强了代码的健壮性。
评论已关闭