• flutter dio 网络封装。记录


    1. import 'package:dio/dio.dart';
    2. import 'config.dart';
    3. class HttpRequest {
    4. static final BaseOptions baseOptions = BaseOptions(
    5. baseUrl: HttpConfig.baseURL, connectTimeout: HttpConfig.timeout);
    6. static final Dio dio = Dio(baseOptions);
    7. static Future<T> request<T>(String url, {
    8. String method = "get",
    9. Map<String, dynamic> params,
    10. Interceptor inter}) async {
    11. // 1.创建单独配置
    12. final options = Options(method: method);
    13. // 全局拦截器
    14. // 创建默认的全局拦截器
    15. Interceptor dInter = InterceptorsWrapper(
    16. onRequest: (options) {
    17. print("请求拦截");
    18. return options;
    19. },
    20. onResponse: (response) {
    21. print("响应拦截");
    22. return response;
    23. },
    24. onError: (err) {
    25. print("错误拦截");
    26. return err;
    27. }
    28. );
    29. List<Interceptor> inters = [dInter];
    30. // 请求单独拦截器
    31. if (inter != null) {
    32. inters.add(inter);
    33. }
    34. // 统一添加到拦截器中
    35. dio.interceptors.addAll(inters);
    36. // 2.发送网络请求
    37. try {
    38. Response response = await dio.request(url, queryParameters: params, options: options);
    39. return response.data;
    40. } on DioError catch(e) {
    41. return Future.error(e);
    42. }
    43. }
    44. }

    config.dart

    class HttpConfig {
      static const String baseURL = "your base url";
      static const int timeout = 10000;
    }

     使用

    static Future> getData() async {
      // 1.发送网络请求
      final url = "/getData";
      final result = await HttpRequest.request(url);
    
      // 2.json转modal
      final mealArray = result["data"];
      List<数据类型> meals = [];
      for (var json in mealArray) {
        meals.add(数据类型.fromJson(json));
      }
      return meals;
    }
  • 相关阅读:
    HashMap 源码分析:jkd7 与 jdk8 的区别
    Android MQTT开发之 Hivemq MQTT Client
    PI/PO Token配置
    运营商三要素核验接口-手机实名验证API
    美团一面:为什么线程崩溃崩溃不会导致 JVM 崩溃
    janus streaming运行说明
    proxmox8.1更换源
    【软考---系统架构设计师】软件架构
    day49-JDBC和连接池05
    如何用CHAT 写会后总结
  • 原文地址:https://blog.csdn.net/congcongguniang/article/details/126292185