美文网首页
Flutter封装Dio实现网络请求

Flutter封装Dio实现网络请求

作者: itfitness | 来源:发表于2022-12-07 07:22 被阅读0次

    引入依赖

    Dio地址:https://pub.dev/packages/dio

    dependencies:
      dio: ^4.0.6
    

    进行封装

    封装一个全局的Dio

    import 'package:dio/dio.dart';
    
    class HttpGlobal{
      static  Dio? _dio;
      static Dio httpClient(){
        if(_dio == null){
          _dio = new Dio();
          _dio?.options = new BaseOptions(
            //配置接口地址
            baseUrl: "https://www.jianshu.com",
            //配置连接超时时间
            connectTimeout: 5000,
            //配置发送超时时间
            sendTimeout: 5000,
            //配置接收超时时间
            receiveTimeout: 5000,
            //配置请求头
            headers: {
    
            },
            //配置contentType
            contentType: Headers.jsonContentType,
            //配置responseType
            responseType: ResponseType.json,
    
          );
          //请求的拦截
          _dio?.interceptors.add(new InterceptorsWrapper(
              onRequest:(options,handler){
                print("请求" + options.extra.toString());
                handler.next(options);
              },
              onError: (e,handler){
                print("请求出错");
                handler.next(e);
              },
              onResponse: (response,handler){
                print("请求返回");
                handler.next(response);
              }
          ));
        }
        return _dio!;
      }
    }
    

    使用

    void test()async{
        var result = await HttpGlobal.httpClient().get("/");
        print(result);
      }
    

    更多的请求方式可以在官方页面查看:https://pub.dev/packages/dio

    相关文章

      网友评论

          本文标题:Flutter封装Dio实现网络请求

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