dio是经常使用到的一个包,为flutter的日常开发提供了很多支持。本文主要描述如何使用Dio封装ajax请求。


dio的依赖:

dependencies:
  dio: 3.0.8


dio包的导入:

import 'package:dio/dio.dart';


dio使用代码示例:

//ajax post
static Future<dynamic> post(String url, Map<String, String> body, {headers = const <String, String>{}, timeout = 15}) {
  //设置发送超时、接收超时以及http header
  BaseOptions options = new BaseOptions(sendTimeout: 5000, receiveTimeout: timeout * 1000, headers: headers);
  Dio dio = Dio(options);
  return dio.post(url, queryParameters: body).then((res) {
    if (res.statusCode == 200) { //http status code
      return res.data;
    } else {
      return {"code": 1, "msg": "服务不可用"};
    }
  }).catchError(((error, stack) {
    //处理异常
    if (error is TimeoutException) {
      return {"code": 1, "msg": "请求超时"};
    } else if (error is DioError) {
      return {"code": 1, "msg": "网络请求失败,请稍后再试"};
    } else {
      return {"code": 1, "msg": "请求异常"};
    }
  }));
}

//ajax get
static Future<dynamic> get(String url, {headers = const <String, String>{}, timeout = 15}) {
  BaseOptions options = new BaseOptions(sendTimeout: 5000, receiveTimeout: timeout * 1000, headers: headers);
  Dio dio = Dio(options);
  return dio.get(url).then((res) {
    if (res.statusCode == 200) {
      return res.data;
    } else {
      return {"code": 1, "msg": "服务不可用"};
    }
  }).catchError((error) {
    if (error is TimeoutException) {
      return {"code": 1, "msg": "请求超时"};
    } else if (error is DioError) {
      return {"code": 1, "msg": "网络请求失败,请稍后再试"};
    }
    return {"code": 1, "msg": "请求异常"};
  });
}