Flutter 网络请求学习(2)

📅 发布时间:2026/7/6 5:20:49 👁️ 浏览次数:
Flutter 网络请求学习(2)
Dio配置flutter pub add dio flutter pub add pretty_dio_logger第二个是dio的日志的包这个包在开发阶段时可以放在dependencies下面要发布的时候可以放到dev_dependencies下面基本使用GET请求importpackage:dio/dio.dart;voidfetchData()async{finaldioDio();// 创建一个实例try{// 一行代码发起请求响应自动解析Responseresponseawaitdio.get(https://api.example.com/data);print(response.data);// 直接是解析后的对象Map 或 List}catch(e){print(请求出错:$e);}}POST请求voidcreatePost()async{finaldioDio();try{Responseresponseawaitdio.post(https://api.example.com/posts,data:{title:Flutter Dio,body:内容...},// 自动转为 JSON);print(创建成功:${response.data});}catch(e){print(创建失败:$e);}}核心功能拦截器允许你在请求发出前相应返回后和发生错误时插入自定义逻辑dio.interceptors.add(InterceptorsWrapper(onRequest:(options,handler){// 请求发送前添加 tokenoptions.headers[Authorization]Bearer your_token;print(请求路径:${options.uri});returnhandler.next(options);// 继续请求},onResponse:(response,handler){// 收到响应后统一处理数据print(响应状态码:${response.statusCode});returnhandler.next(response);// 继续传递},onError:(DioExceptione,handler){// 发生错误时统一处理异常if(e.response?.statusCode401){// 跳转到登录页}returnhandler.next(e);// 继续传递错误},));取消请求在页面关闭时取消未完成的请求finalcancelTokenCancelToken();voidfetchData(){dio.get(https://api.example.com/large-data,cancelToken:cancelToken).then((response)print(response.data)).catchError((e){if(CancelToken.isCancel(e)){print(请求已被取消:${e.message});}});}// 页面销毁时比如在 dispose 中overridevoiddispose(){cancelToken.cancel(页面已退出取消请求);super.dispose();}文件上传与进度监听voiduploadFile()async{finalformDataFormData.fromMap({name:头像,file:awaitMultipartFile.fromFile(/path/to/photo.jpg,filename:avatar.jpg),});awaitdio.post(https://api.example.com/upload,data:formData,onSendProgress:(int sent,int total){if(total!-1){double progresssent/total*100;print(上传进度:${progress.toStringAsFixed(1)}%);}},);}当需要将本地文件如图片、文档作为表单的一部分上传时必须将文件数据包装成 MultipartFile 对象FormData 可以包含多个 MultipartFile 字段从而实现多文件上传。错误处理Dio将所有异常封装为DioException可以通过e.type判断具体错误类型封装Dio实例正常使用时通常是将其封装为一个单例工具类classHttpUtil{staticfinalHttpUtil_instanceHttpUtil._internal();factoryHttpUtil()_instance;lateDiodio;HttpUtil._internal(){dioDio(BaseOptions(baseUrl:https://api.example.com,connectTimeout:constDuration(seconds:10),receiveTimeout:constDuration(seconds:10),));dio.interceptors.add(LogInterceptor(responseBody:true));// 开发日志// 可添加更多拦截器如认证}FutureResponseget(Stringpath)async{try{returnawaitdio.get(path);}catch(e){// 统一错误处理rethrow;}}}// 使用: HttpUtil().get(/user/info)