在Flutter中实现网络请求有很多模块,可以使用http模块,也可以使用dio模块。
具体的用法在https://pub.dev/上面有,我们以前的的项目中用的是Dio库,它支持get post put delete还支持文件的上传下载。
- import ‘package:dio/dio.dart’;
-
- final dio = Dio();
-
- void getHttp() async {
- final response = await dio.get(‘https://dart.dev’);
- print(response);
- }
-
- import ‘package:dio/dio.dart’;
-
- class HttpsClient {
- static String domain = “https://xiaomi.itying.com/”;
- static Dio dio = Dio();
- HttpsClient() {
- dio.options.baseUrl = domain;
- dio.options.connectTimeout = const Duration(milliseconds: 5000); //5s
- dio.options.receiveTimeout = const Duration(milliseconds: 5000);
- }
-
- Future get(apiUrl) async {
- try {
- var response = await dio.get(apiUrl);
- return response;
- } catch (e) {
- print(“请求超时”);
- return null;
- }
- }
-
- Future post(String apiUrl, {Map? data}) async {
- try {
- var response = await dio.post(apiUrl, data: data);
- return response;
- } catch (e) {
- print(“请求超时”);
- return null;
- }
- }
- }