Flutter学习

Flutter中的网络请求库Dio简单使用

2020-11-18  本文已影响0人  刘铁崧

pubspec.yaml配置dio: ^版本号

dependencies:
  flutter:
    sdk: flutter

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^0.1.3
  dio: ^3,0.9

执行Pub get
导入头文件

import 'package:dio/dio.dart';

get请求与post请求

    // get请求
    dio.get("https://httpbin.org/get").then((value){
      print(value);
    });
    // post请求
    dio.post("https://httpbin.org/post").then((value){
      print(value);
    });

简单封装
封装请求类:

import 'package:cyeshop/cy_http_config.dart';
import 'package:dio/dio.dart';

class CYHttpRequest{
  //有3中超时:连接超时、发送超时、接受服务器回应超时
  static final BaseOptions baseOptions = BaseOptions(baseUrl:CYHTTPConfig.baseURL ,connectTimeout:CYHTTPConfig.connectTimeOut );
  static final Dio dio = Dio();
  static Future<T> request<T>(String url,{String method = "get",Map<String,dynamic> params,Interceptor interceptor}) async {
    // 创建请求配置
    final option = Options(method: method);
    // 创建全局的拦截器(默认拦截器)
    // onrequest:请求拦截
    // onResponse: 响应拦截
    // onError: 错误拦截
    Interceptor defaultInterceptor = InterceptorsWrapper(
      onRequest:(options){//请求拦截
        print("请求拦截");
        return options;
      },
      onResponse: (response){
        print("响应拦截");
        return response;//响应拦截
      },
      onError: (error){//错误拦截
        print("错误拦截");
        return error;
      }
    );
    List<Interceptor> interceptors = [defaultInterceptor];
    if(interceptor != null){//将自定义拦截器加入
      interceptors.add(interceptor);
    }
    // 统一添加到拦截区中
    dio.interceptors.addAll(interceptors);
    // 发送请求
    // Response response = await dio.request(url,queryParameters: params,options: option);
    // return response.data;
    try{
      Response response = await dio.request(url,queryParameters: params,options: option);
      return response.data;
    }on DioError catch(error){
      return Future.error(error);
    }
  }
  // static void get(String url){
  //  
  // }
  // static void post(String url){
  //
  // }
}

封装配置信息类:

class CYHTTPConfig{
  static const String baseURL = "https://httpbin.org";
  static const int connectTimeOut = 5000;//毫秒
}

调用:

CYHttpRequest.request(CYHTTPConfig.baseURL+"/get",params: {"name":"cy" },interceptor: InterceptorsWrapper(
      onRequest: (request){
        print("外部请求拦截");
        return request;
      },onResponse: (response){
        print("外部响应拦截");
        return response;
      },onError: (error){
      print("外部错误拦截");
      }
    )).then((value){
      print("获取数据");
    }).catchError((error){

    });
上一篇下一篇

猜你喜欢

热点阅读