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'); }); }

本猿是個新手,決定吧現在學習的每一步都記錄下來,也都盡量寫一些方便擴展,思路明晰的封裝包,不為別的,只為日后自己可以看懂(哈哈)。

所以有什么不對的地方大家可以指出,不要噴,有話好好說(嘿)!

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM