天天看點

Flutter學習(四)Http請求庫 dio 代碼封裝

Flutter學習(四)Http請求庫 dio代碼封裝

第一步 依賴庫
  1. 打開flutter package網站,入口,找到dio這個元件,檢視最新版本
    Flutter學習(四)Http請求庫 dio 代碼封裝
  2. 打開 項目根目錄下 ** pubspec.yaml ** 檔案
    Flutter學習(四)Http請求庫 dio 代碼封裝
  3. 添加庫名,添加庫名
    Flutter學習(四)Http請求庫 dio 代碼封裝

最好是填寫 any(** 添加相容版本 **),也或者直接從網站複制最新版本即可,

執行 packages get 指令,安裝依賴

  1. 代碼部分
import 'package:dio/dio.dart';

import 'config.dart';//用于配置公用常量

class Http{
  static Http instance;
  static String token;
  static Config _config = new Config();
  static Dio _dio;
  Options _options;

  static Http getInstance(){
    print("getInstance");
    if(instance == null){
      instance  = new Http();
    }
  }

  Http(){
  		// 初始化 Options
    _options =new Options(
      baseUrl: _config.base_url,
      connectTimeout: _config.connectTimeout,
      receiveTimeout: _config.receiveTimeout,
      headers: {}
    );

    _dio = new Dio(_options);
		
	//發送請求攔截處理,例如:添加token使用
    _dio.interceptor.request.onSend = (Options options) async{

      print(options.baseUrl);
      return options;
    };
	
	//請求成功攔截,簡化代碼中調用難度
    _dio.interceptor.response.onSuccess = (Response response) async{
      print(response.statusCode);
      return response;
    };
		//請求失敗攔截
    _dio.interceptor.response.onError = (DioError e) {
      print(e);
      return e;
    };
  }



   // get 請求封裝
  get(url,{ options, cancelToken, data=null}) async {
    print('get:::url:$url ,body: $data');
    Response response;
    try{
      response = await _dio.get(
          url,
          data:data,
          cancelToken:cancelToken
      );
    }on DioError catch(e){
      if(CancelToken.isCancel(e)){
        print('get請求取消! ' + e.message);
      }else{
        print('get請求發生錯誤:$e');
      }
    }
    return response.data;
  }
	
	// post請求封裝
  post(url,{ options, cancelToken, data=null}) async {
    print('post請求::: url:$url ,body: $data');
    Response response;

    try{
      response = await _dio.post(
          url,
          data:data !=null ? data : {},
          cancelToken:cancelToken
      );
      print(response);
    }on DioError catch(e){
      if(CancelToken.isCancel(e)){
        print('get請求取消! ' + e.message);
      }else{
        print('get請求發生錯誤:$e');
      }
    }
    return response.data;
  }
}
           
  1. 調用

    頁面中引入檔案:

    Flutter學習(四)Http請求庫 dio 代碼封裝
import ‘util/http.dart’;
var response = await Http().get(
                "tree/json",
                data: {'pageIndex': 1, 'pageSize': 10});
    print(response);
           

6.解析資料

官方推薦使用json_serializable進行資料解析

  1. 下一章節貼上json_serializable的使用方法供大家參考,歡迎指正和互相交流;