flutter 网络请求Dio封装
封装网络请求的几个好处:
1、便于统一配置请求参数,如header,公共参数,加密规则等
2、方便调试,日志打印
3、优化代码性能,避免到处滥new对象,构建全局单例
4、简化请求步骤,只暴露需要的响应数据,而对错误的响应统一回调
5、对接口数据的基类封装,简化解析流程
添加依赖:
dependencies:
dio: ^3.0.10
pub地址:https://pub.flutter-io.cn/packages/dio
效果示例:
首先创建一个Dio实体类dioUtils.dart
代码如下,尽量详细明了的解释。
import 'package:connectivity/connectivity.dart'; //网络监听组件 import 'package:cookie_jar/cookie_jar.dart'; import 'package:dio/dio.dart'; import 'package:dio_cookie_manager/dio_cookie_manager.dart'; import 'package:flutter_app/http/error_handle.dart'; import 'package:flutter_app/route/application.dart'; //规定函数类型 typedef BackError = Function(int code, String msg); class DioUtil{ Dio dio; //服务器ip static final String BASEURL = ''; //普通格式的header static final Map<String, dynamic> headers = { "Accept":"application/json", "Content-Type":"application/x-www-form-urlencoded", }; //json格式的header static final Map<String, dynamic> headersJson = { "Accept":"application/json", "Content-Type":"application/json; charset=UTF-8", }; //构造实体类 DioUtil(){ BaseOptions options = BaseOptions(); //注册请求服务器 options.baseUrl = BASEURL; //设置连接超时单位毫秒 options.connectTimeout=5000; // 响应流上前后两次接受到数据的间隔,单位为毫秒。如果两次间隔超过[receiveTimeout], // [Dio] 将会抛出一个[DioErrorType.RECEIVE_TIMEOUT]的异常. // 注意: 这并不是接收数据的总时限. options.receiveTimeout=3000; //设置请求超时单位毫秒 options.sendTimeout = 5000; //如果返回数据是json(content-type), // dio默认会自动将数据转为json, // 无需再手动转](https://github.com/flutterchina/dio/issues/30) options.responseType = ResponseType.plain; options.headers = headers; dio = Dio(options); dio.interceptors.add(CookieManager(CookieJar())); } void get(String url,{Map<String,dynamic> data,success,BackError error}) async{ _isNet(error); ApplicationPrint.printInfo('get请求启动! url:$url ,body: $data'); Response response; try{ if(data==null){ response = await dio.get(url); }else{ response = await dio.get(url,queryParameters:data); } if(response.statusCode == ExceptionHandle.success){ success(response.data); }else{ error(response.statusCode,"数据服务出现异常!"); } }on DioError catch (e){ final NetError netError = ExceptionHandle.handleException(e); error(netError.code,netError.msg); ApplicationPrint.printInfo('get请求发生错误:${netError.code}//${netError.msg}'); } } void post(String url,{Map<String,dynamic> data,success,BackError error})async{ ApplicationPrint.printInfo('post请求启动! url:$url ,body: $data'); Response response; try{ if(data==null){ response = await dio.post(url); }else{ response = await dio.post(url,data: data); } if(response.statusCode == 200){ success(response.data); }else{ error(response.statusCode,"数据服务出现异常!"); } }on DioError catch (e){ final NetError netError = ExceptionHandle.handleException(e); error(netError.code,netError.msg); ApplicationPrint.printInfo('post请求发生错误:${netError.code}//${netError.msg}'); } } // 判断是否有网 void _isNet(BackError error) async{ //没有网络 var connectivityResult = await (Connectivity().checkConnectivity()); if (connectivityResult == ConnectivityResult.none) { error(ExceptionHandle.net_error, '网络异常,请检查你的网络!'); return; } } }
写一个全局静态文件,实例化一次。application.dart
class ApplicationPrint{ //全局日志打印设置 true 显示,false显示 static const bool _IsPrint = true; static void printInfo(info){ if(_IsPrint){ print(info); } } } class ApplicationDioUtils{ static DioUtil dioUtil; //注册全局dio }
在程序启动时初始化。
void main() { final router =FluroRouter(); Routes.configureRouts(router); ApplicationRouter.router = router; ApplicationDioUtils.dioUtil = DioUtil();//实例化dio runApp(MyApp()); }
发送网络请求:post and get
_getUser(){ var url = 'https://www.fastmock.site/mock/a8fefcc6e356f684b8f80984543c1cac/flutter/getUserInfo';
//get 请求,参数为 请求地址、请求参数、请求成功之后的回调,以及出现异常时的监听 ApplicationDioUtils.dioUtil.get(url,data:{"user":"zhangsan"},success: (data){ ApplicationPrint.printInfo("_getUser"); ApplicationPrint.printInfo(data); ApplicationPrint.printInfo(data is Map); ApplicationPrint.printInfo(data is String); String name = '{"":""}'; ApplicationPrint.printInfo(data is String); ApplicationPrint.printInfo( jsonDecode(data)['age']); },error: (code,msg){ ApplicationPrint.printInfo('请求出现异常$code'); }); } _getUser2(){ var url = 'https://www.fastmock.site/mock/a8fefcc6e356f684b8f80984543c1cac/flutter/postInfo';
ApplicationDioUtils.dioUtil.post(url,data:{'user':'name','pwd':123},success: (data){ ApplicationPrint.printInfo("_getUser2"); ApplicationPrint.printInfo(data); ApplicationPrint.printInfo(data is Map); ApplicationPrint.printInfo(data is String); json.decode(data.toString()); // ApplicationPrint.printInfo( jsonDecode(data)[0]['name']); ApplicationPrint.printInfo( json.decode(data.toString())); },error: (code,msg){ ApplicationPrint.printInfo('请求出现异常$code'); }); }
本猿是个新手,决定吧现在学习的每一步都记录下来,也都尽量写一些方便扩展,思路明晰的封装包,不为别的,只为日后自己可以看懂(哈哈)。
所以有什么不对的地方大家可以指出,不要喷,有话好好说(嘿)!