美文网首页Flutter学习
Flutter工具学习与拓展1--网络请求封装(dio)

Flutter工具学习与拓展1--网络请求封装(dio)

作者: 那年那月那花儿 | 来源:发表于2019-06-27 15:55 被阅读0次

    学习flutter已有一段时间了, 想找个项目练练手, 准备项目框架:

    1. 网络请求封装--dio+json_serializable
    2. 路由--flutter-ARoute
    3. 状态机管理--flutter_redux=>fish_redux

    第一章---简易常用网络请求封装

    导入库

      dio: ^2.1.7
      json_serializable: ^3.0.0
      build_runner: ^1.6.0
      fluttertoast: ^3.1.0
    

    封装网络请求 单例 netUtil类

    import 'package:dio/dio.dart';
    import 'dart:convert';
    import 'package:fluttertoast/fluttertoast.dart';
    
    class NetworkUtil {
      static const String k_GET = "get";
      static const String k_POST = "post";
      static const String k_DELETE = "delete";
      static const String k_PUT = "put";
    
      /* 
      warning: 下面两个参数是根据封装的格式进行调整的, 如下面数据格式是:{s(就是常见的status):1, m:ok, d(数据, data):{}}, 具体可参考下方实例get请求返回的数据格式
      */
      static const String k_DATA = "d";//数据, 类似data
      static const String k_CODE = "s";//状态码, 类似status
      static const String k_MSG  = "m";//提示语, 类似msg
    
     /* 
      封装单例, 类似于iOS和Android
      */
      Dio dio;
      static NetworkUtil _instance;
      static NetworkUtil getInstance() {
        if (_instance == null) {
          _instance = NetworkUtil();
        }
        return _instance;
      }
    
      NetworkUtil() {
        dio = new Dio(BaseOptions(
          headers: {},
          connectTimeout: 5000,
          receiveTimeout: 100000,
          //baseUrl: "http://baidu.com"
        ));
      }
    
      get(String url, Function successCallBack,
          {params, Function errorCallBack}) async {
        _requestHttp(url, successCallBack, k_GET, params, errorCallBack);
      }
    
      post(String url, Function successCallBack,
          {params, Function errorCallBack}) async {
        _requestHttp(url, successCallBack, k_POST, params, errorCallBack);
      }
    
      put(String url, Function successCallBack,
          {params, Function errorCallBack}) async {
        _requestHttp(url, successCallBack, k_PUT, params, errorCallBack);
      }
    
      delete(String url, Function successCallBack,
          {params, Function errorCallBack}) async {
        _requestHttp(url, successCallBack, k_PUT, params, errorCallBack);
      }
    
      _requestHttp(String url, Function successCallBack,
          [String method, FormData params, Function errorCallBack]) async {
        String errorMsg = "";
        int code;
    
        try {
          Response response;
          _addStartHttpInterceptor(dio);
          if (method == k_GET) {
            if (params != null && params.isNotEmpty) {
              response = await dio.get(url, queryParameters: params);
            } else {
              response = await dio.get(url);
            }
          } else if (method == k_POST) {
            if (params != null && params.isNotEmpty) {
              response = await dio.post(url, queryParameters: params);
            } else {
              response = await dio.post(url);
            }
          } else if (method == k_PUT) {
            if (params != null && params.isNotEmpty) {
              response = await dio.put(url, queryParameters: params);
            } else {
              response = await dio.put(url);
            }
          } else if (method == k_DELETE) {
            if (params != null && params.isNotEmpty) {
              response = await dio.delete(url, queryParameters: params);
            } else {
              response = await dio.delete(url);
            }
          }
          code = response.statusCode;
          if (code != 200) {
            errorMsg = '错误码: ' + code.toString() + ', ' + response.data.toString();
            _error(errorCallBack, errorMsg);
            return;
          }
    
          String dataStr = json.encode(response.data);
          Map<String, dynamic> dataMap = json.decode(dataStr);
          //此处判断弹出错误信息的条件, 注意k_Code对应异常的值
          if (dataMap != null && dataMap[k_CODE] != 1) {
            errorMsg = dataMap[k_MSG].toString();
            _error(errorCallBack, errorMsg);
            return;
          }
    
          if (successCallBack != null) {
            //此处需要注意, 该方法现在传递的是整体的数据, 如需要可根据返回数据的样式, 回调调整
            successCallBack(dataMap);
          }
        } catch (e) {
          _error(errorCallBack, e.toString());
        }
      }
    
    /*
      错误处理的地方
    */
      _error(Function errorCallBack, String error) {
        Fluttertoast.showToast(
            msg: error.toString(),
            toastLength: Toast.LENGTH_SHORT,
            gravity: ToastGravity.CENTER);
        if (errorCallBack != null) {
          errorCallBack(error);
        }
      }
    
    /*
      对参数数据进行二次处理, 加密算法
    */
      _addStartHttpInterceptor(Dio dio) {
        dio.interceptors
            .add(InterceptorsWrapper(onRequest: (RequestOptions options) {
          //请求前的操作, 通常会在这里进行参数的处理, 比如加密, 添加参数等
          Map<String, dynamic> headers = options.headers;
          Map<String, dynamic> body = options.data;
          /*
          body['addParam'] = 'aaaaaaaa';
          */
          print('''$headers
          $body''');
          return options;
        }));
      }
    }
    

    上面根据数据格式进行封装, 使用者请根据自身项目网络请求返回的常规格式进行调整
    此文对应demo结构


    F0A92536-0BC6-416E-B7D1-2FF0B01E284B.png
    var url =
            'https://timeline-merger-ms.juejin.im/v1/get_entry_by_rank?src=web&before=26.723845333467&limit=20&category=all';
        NetworkUtil.getInstance().get(url, (data) {
          print(data);
          setState(() {
    //将在第二章记录json_serializable的使用
         //   _indexCell = IndexCell.fromJson(data);
          });
        });
    

    相关文章

      网友评论

        本文标题:Flutter工具学习与拓展1--网络请求封装(dio)

        本文链接:https://www.haomeiwen.com/subject/krhuqctx.html