美文网首页工作生活
基于最新dio2.1.7 flutter网络请求库二次封装

基于最新dio2.1.7 flutter网络请求库二次封装

作者: YannChee | 来源:发表于2019-07-02 20:27 被阅读0次

基于最新dio2.1.7 flutter网络请求库二次封装成一个网络请求工具类,这里命名为HttpTool

import 'dart:io';
import 'package:dio/dio.dart';

class Method {
  static final String get = "GET";
  static final String post = "POST";
}

class HttpTool {
  static final HttpTool _instance = HttpTool._init();
  static Dio _dio;
  static BaseOptions _options = getDefaultOptions();

  factory HttpTool() {
    return _instance;
  }

  HttpTool._init() {
    _dio = new Dio();
  }

  static BaseOptions getDefaultOptions() {
    BaseOptions options = BaseOptions();
    options.connectTimeout = 10 * 1000; // 请求超时10秒
    options.receiveTimeout = 30 * 1000; // 响应超时30秒
    // TODO: 其它option配置

    return options;
  }

  setOptions(BaseOptions options) {
    _options = options;
    _dio.options = _options;
  }

  dynamic get(String path, {pathParams, data, Function errorCallback}) {
    return request(path, method: Method.get, pathParams: pathParams, data: data, errorCallback: errorCallback);
  }

  dynamic post(String path, {pathParams, data, Function errorCallback}) {
    return request(path, method: Method.post, pathParams: pathParams, data: data, errorCallback: errorCallback);
  }

  dynamic request(String path,{String method, Map pathParams, data, Function errorCallback}) async {

    Response response = await _dio.request(path, data: data, options: Options(method: method));

    if(response.statusCode != HttpStatus.ok) {
      errorCallback == null ??  errorCallback(response.statusCode);
      return null;
    }
    
    try {
      return response.data;
    } catch(e) {
      print(e);
      return null;
    }
    
  }
}

则DAO层调用市里代码为

import 'http_tool.dart';

class TestDao {
  static dynamic requestForData() async {
    String dataURL = "https://api.github.com/orgs/raywenderlich/members";
    dynamic responseData = await HttpTool().get(dataURL);
    return responseData;
  }
}

页面网络请求调用DAO层的示例代码为:

_loadData() async {
      dynamic responseData = await TestDao.requestForData();

      setState(() {
        final List membersJSONs = responseData as List;
        for (var memberJSON in membersJSONs) {
          final  TestModel model = TestModel.fromJson(memberJSON);
          _members.add(model);
        }
      });
  }

相关文章

网友评论

    本文标题:基于最新dio2.1.7 flutter网络请求库二次封装

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