Flutter - 网络请求

2022-12-08  本文已影响0人  hyq1101

1、dio三方库
dio是一个强大的Dart Http请求库,支持Restful API、FormData、拦截器、请求取消、Cookie管理、文件上传/下载、超时、自定义适配器等...
dio三方库github地址:https://github.com/flutterchina/dio

2、添加依赖
使用dio三方库需要先在pubspec.yaml中依赖它


image.png

3、dio库封装
confic.dart

class HttpConfig {
  static const String baseUrl = "";
  static const int timeout = 超时时长;
}

http_request.dart

import 'package:dio/dio.dart';
import 'package:learn_flutter/service/config.dart';

class HttpRequest {
  static final BaseOptions baseOptions = BaseOptions(baseUrl: HttpConfig.baseUrl, connectTimeout: HttpConfig.timeout);
  static final Dio dio = Dio(baseOptions);
  static Future<T> request<T>(String url, {String method = "get", Map<String, dynamic>? params, Interceptor? inter}) async {
    // 1、创建单独配置
    final options = Options(method: method);
    // 全局拦截器
    // 创建默认的全局拦截器
    // 2.添加第一个拦截器
    Interceptor dInter = InterceptorsWrapper(
        onRequest: (options, handler) {
          print("请求拦截");
          // Do something before request is sent
          return handler.next(options); //continue
          // 如果你想完成请求并返回一些自定义数据,你可以resolve一个Response对象 `handler.resolve(response)`。
          // 这样请求将会被终止,上层then会被调用,then中返回的数据将是你的自定义response.
          //
          // 如果你想终止请求并触发一个错误,你可以返回一个`DioError`对象,如`handler.reject(error)`,
          // 这样请求将被中止并触发异常,上层catchError会被调用。
        },
        onResponse: (response, handler) {
          print("响应拦截");
          // Do something with response data
          return handler.next(response); // continue
          // 如果你想终止请求并触发一个错误,你可以 reject 一个`DioError`对象,如`handler.reject(error)`,
          // 这样请求将被中止并触发异常,上层catchError会被调用。
        },
        onError: (DioError e, handler) {
          print("错误拦截");
          // Do something with response error
          return  handler.next(e);//continue
          // 如果你想完成请求并返回一些自定义数据,可以resolve 一个`Response`,如`handler.resolve(response)`。
          // 这样请求将会被终止,上层then会被调用,then中返回的数据将是你的自定义response.
        }
    );


    List<Interceptor> inters = [dInter];
    if (inter != null) {
      inters.add(inter);
    }
    dio.interceptors.addAll(inters);
    // 2、发送网络请求
    try {
      Response response = await dio.request(url, queryParameters: params, options: options);
      return response.data;
    } on DioError catch(e) {
      return Future.error(e);
    }
  }
}

代码调用:

HttpRequest.request("接口地址", method: "get",).then((value) {
      print(value);
    }).catchError((onError) {
      print(onError);
    });
上一篇 下一篇

猜你喜欢

热点阅读