Flutter Dio網(wǎng)絡(luò)請(qǐng)求

Dart packages
  1. 網(wǎng)絡(luò)請(qǐng)求使用dio.dart
  2. 數(shù)據(jù)解析使用json_serializable和json_annotation
  3. 創(chuàng)建.g.dart使用build_runner 使用方法
  4. 監(jiān)聽(tīng)事件使用 event_bus.dart
  5. Dart packages地址
文件相關(guān)
  1. PXAdress.dart 請(qǐng)求地址相關(guān)
  2. PXRequest.dart 具體請(qǐng)求類
  3. PXResultModel 請(qǐng)求數(shù)據(jù)對(duì)象
  4. YYRequestManager 請(qǐng)求管理類
  5. YYResultCode 狀態(tài)碼
  6. YYResultErrorEvent錯(cuò)誤時(shí)間類
  7. YYResultModel基礎(chǔ)數(shù)據(jù)對(duì)象
  8. YYConfig配置文件
配合界面使用
// 界面使用
  void _requestData() async {
    UserInfo userInfo = await PXRequest.px_getuser();
    setState(() {
      _userInfo = userInfo;
    });
  }

dependencies:
  flutter:
    sdk: flutter

  flutter_spinkit: "^2.1.0"  # load more loading
  dio: 1.0.6  #無(wú)網(wǎng)絡(luò)請(qǐng)求
  json_annotation: ^1.2.0 #json_serializable助手

dev_dependencies:
  flutter_test:
    sdk: flutter

  build_runner: ^1.0.0  #創(chuàng)建.g.dart
  json_serializable: ^1.5.1  #序列化json
import 'package:dio/dio.dart';
import 'package:connectivity/connectivity.dart';

import 'dart:collection';

import 'package:ly_app/net/YYResultModel.dart';
import 'package:ly_app/net/YYResultCode.dart';
import 'package:ly_app/config/YYConfig.dart';

class YYRequestManager {
  static String baseUrl = ""; 
  static Map<String, String> baseHeaders = {
    "packageName":"com.puxin.financePlanner",
    "appName":"",
    "version":"1.8.7.3",
    "os":"ios",
    "channel":"appStore",
    "platform":"11.1999998092651",
    "model":"",
    "factory":"apple",
    "screenSize":"(0.0, 0.0, 375.0, 667.0)",
    "clientId":"15444",
    "token":"7fc30ec2206ec3135ca9d33d11406b36b048e4950836a678c4642e492",
    "sign":"",
    "pid":"pid",
    "registrationId":"pid",
  };

  static const CONTENT_TYPE_JSON = "application/json";
  static const CONTENT_TYPE_FORM = "application/x-www-form-urlencoded";
  static Map optionParams = {
    "timeoutMs": 15000,
    "token": null,
    "authorizationCode": null,
  };

  static requestPost(url, params, {noTip = false}) async {
    Options option = new Options(method: "post");
    return await requestBase(url, params, baseHeaders, option, noTip: noTip);
  }

  static requestBase(url, params, Map<String, String>header, Options option, {noTip = false}) async {
    // 判斷網(wǎng)絡(luò)
    var connectivityResult = await (new Connectivity().checkConnectivity());
    if (connectivityResult == ConnectivityResult.mobile) {

    } else if (connectivityResult == ConnectivityResult.wifi) {
      
    } else if (connectivityResult == ConnectivityResult.none){
      return YYResultModel(YYResultErrorEvent(YYResultCode.NETWORK_ERROR, "請(qǐng)檢查網(wǎng)絡(luò)"), false, YYResultCode.NETWORK_ERROR);
    }

    //處理請(qǐng)求頭
    Map<String, String> headers = new HashMap();
    if (header!=null) {
      headers.addAll(header);
    }

    //options處理
    if (option != null) {
      option.headers = headers;
    } else{
      option = new Options(method: "get");
      option.headers = headers;
    }
    option.baseUrl = baseUrl;
    option.connectTimeout = 15000;

    var dio = new Dio();
    Response response;
    try {
      response = await dio.request(url, data: params, options: option);
    } on DioError catch (error) {
      // 請(qǐng)求錯(cuò)誤處理
      Response errorResponse;
      if (error.response != null) {
        errorResponse = error.response;
      } else {
        errorResponse = new Response(statusCode: 666);
      }
      // 超時(shí)
      if (error.type == DioErrorType.CONNECT_TIMEOUT) {
        errorResponse.statusCode = YYResultCode.NETWORK_TIMEOUT;
      }
      // debug模式才打印
      if (YYConfig.DEBUG) {
        print('請(qǐng)求異常: ' + error.toString());
        print('請(qǐng)求異常url: ' + url);
        print('請(qǐng)求頭: ' + option.headers.toString());
        print('method: ' + option.method);
      }
      // 返回錯(cuò)誤信息
      return new YYResultModel(YYResultCode.errorHandleFunction(errorResponse.statusCode, error.message, noTip), false, errorResponse.statusCode);
     };

    // debug模式打印相關(guān)數(shù)據(jù)
    if (YYConfig.DEBUG) {
      print('請(qǐng)求url: ' + url);
      print('請(qǐng)求頭: ' + option.headers.toString());
      if (params != null) {
        print('請(qǐng)求參數(shù): ' + params.toString());
      }
      if (response != null) {
        print('返回參數(shù): ' + response.toString());
      }
    }

    try {
      if (response.statusCode == 200 || response.statusCode == 201) {
        return new YYResultModel(response.data, true, YYResultCode.SUCCESS, headers: response.headers);
      }
    } catch (error) {
      print(error.toString() + url);
      return new YYResultModel(response.data, false, response.statusCode, headers: response.headers);
    }
    return new YYResultModel(YYResultCode.errorHandleFunction(response.statusCode, "", noTip), false, response.statusCode);
  }
}
import 'YYRequestManager.dart';
import 'YYResultModel.dart';

import 'package:ly_app/Model/UserInfo.dart';

import 'PXResultModel.dart';

class PXRequest {

  static px_getuser() async {
    YYResultModel model = await YYRequestManager.requestPost("/employee/getuser", null);
    
    PXResultModel px_model = PXResultModel.init(model.data);

    UserInfo userInfo = UserInfo.fromJson(px_model.result);

    return userInfo;
  }
}

class YYResultModel {
  var data;
  bool success;
  int code;
  var headers;

  YYResultModel(this.data, this.success, this.code, {this.headers});
}

class PXResultModel {
  String message;
  var result;
  int returnCode;
  String token;

  PXResultModel(this.message, this.result, this.returnCode, this.token);

  static PXResultModel init(Map json) {
    return PXResultModel(json["message"], json["result"], json["returnCode"], json["token"]);
  }
}
import 'package:event_bus/event_bus.dart';

class YYResultCode {
  ///網(wǎng)絡(luò)錯(cuò)誤
  static const NETWORK_ERROR = -1;

  ///網(wǎng)絡(luò)超時(shí)
  static const NETWORK_TIMEOUT = -2;

  ///網(wǎng)絡(luò)返回?cái)?shù)據(jù)格式化一次
  static const NETWORK_JSON_EXCEPTION = -3;

  static const SUCCESS = 200;

  static final EventBus eventBus = new EventBus();

  static errorHandleFunction(code, message, noTip) {
    if(noTip) {
      return message;
    }
    eventBus.fire(new YYResultErrorEvent(code, message));
    return message;
  }
}
class YYResultErrorEvent {
  final int code;

  final String message;

  YYResultErrorEvent(this.code, this.message);
}

class PXAdress {
  static getuser() {
    return "";
  }
}

class YYConfig {
  static bool DEBUG = true;
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容