Flutter Minimalist Dio Component Secondary Packaging Documentation


foreword

This document describes how to simplify the process of network requests by re-encapsulating Flutter Dio components. Through encapsulation, we can improve code reusability, simplify calling methods, and add some common functions to make network requests easier to manage and maintain.


1. Add dependencies

First, make sure your Flutter project has added the Dio dependency. In the project's pubspec.yaml file, add the following dependencies:

dependencies:
  dio: ^4.0.0

Then run flutter pub get to get the latest dependencies.

Second, create a package class

Create a new Dart class to encapsulate the functionality of the Dio component. For example, we can create a class called ApiService.

import 'package:dio/dio.dart';

class ApiService {
    
    
  final Dio _dio;

  ApiService() : _dio = Dio() {
    
    
    // 在这里可以添加一些公共配置,如请求超时时间、拦截器等
    _dio.options.baseUrl = 'https://api.example.com';
    _dio.options.connectTimeout = 5000; // 设置请求超时时间为5秒
  }

  // 在这里添加封装后的网络请求方法
  Future<Response> fetchData(String path, {
    
    Map<String, dynamic>? params}) async {
    
    
    try {
    
    
      final response = await _dio.get(path, queryParameters: params);
      return response;
    } catch (e) {
    
    
      throw Exception('网络请求失败');
    }
  }
}

In the sample code above, we created a class called ApiService, which contains a _dio instance to handle network requests. In the constructor, we can do some common configuration, such as setting the base URL, request timeout, etc.

Next, in the ApiService class, we added a fetchData method to send a GET request. This method accepts a path parameter and an optional parameter Map for passing query parameters. Inside the method, we use the get method of the Dio component to send the request and return the response.

You can continue to add other types of request methods (such as POST, PUT, DELETE, etc.) or other functions according to actual needs.

3. Use encapsulation class

In your Flutter project, you can use the encapsulated network request method by instantiating the ApiService class. Here is a simple example:

final apiService = ApiService();

void fetchData() async {
    
    
  try {
    
    
    final response = await apiService.fetchData('/data', params: {
    
    'id': 1});
    // 处理响应结果
    print(response.data);
  } catch (e) {
    
    
    // 处理异常
    print(e.toString());
  }
}

In the above example, we first create an ApiService instance apiService, and then use it to call the encapsulated fetchData method to make network requests. In the catch block, we handle possible exceptions and print out error messages.

According to actual needs, you can further improve and expand the functions of the encapsulation class to meet the specific requirements of the project.

4. Interceptor

The Dio component supports interceptors, which you can handle before the request is sent or after the response is returned. This provides convenience for adding functions such as public parameters and authentication.

The following is an example that demonstrates how to use an interceptor to add a Token in the request header.

class ApiService {
    
    
  final Dio _dio;

  ApiService() : _dio = Dio() {
    
    
    // 在这里可以添加一些公共配置,如请求超时时间、拦截器等
    _dio.options.baseUrl = 'https://api.example.com';
    _dio.options.connectTimeout = 5000; // 设置请求超时时间为5秒

    // 添加拦截器
    _dio.interceptors.add(
      InterceptorsWrapper(
        onRequest: (options, handler) {
    
    
          // 在请求头中添加 Token
          final token = getToken(); // 获取 Token 的方法,根据实际情况替换
          options.headers['Authorization'] = 'Bearer $token';

          return handler.next(options);
        },
      ),
    );
  }

  // ...
}

In the above example, we implement the interceptor functionality by creating an instance of InterceptorsWrapper and adding it to _dio's list of interceptors. In the onRequest callback, we can modify the request or add processing logic. In this example, we add a field called "Authorization" in the request header and set its value as Token.

You can add other interceptors to implement various functions according to actual needs, such as logging, caching, etc.

5. Error handling

In network requests, error handling is very important. You can catch and handle different error conditions through the Dio component's error type.

Here is an example showing how to handle network request exceptions:

class ApiService {
    
    
  // ...

  Future<Response> fetchData(String path, {
    
    Map<String, dynamic>? params}) async {
    
    
    try {
    
    
      final response = await _dio.get(path, queryParameters: params);
      return response;
    } catch (e) {
    
    
      if (e is DioError) {
    
    
        // DioError 是 Dio 组件的异常类型,可以根据不同的错误类型进行处理
        if (e.type == DioErrorType.connectTimeout) {
    
    
          throw Exception('连接超时,请检查网络连接');
        } else if (e.type == DioErrorType.response) {
    
    
          // 如果服务器返回了错误响应,可以通过 e.response 来获取响应信息
          final statusCode = e.response?.statusCode;
          final errorMessage = e.response?.statusMessage;
          throw Exception('请求失败:$statusCode $errorMessage');
        } else {
    
    
          throw Exception('请求失败,请稍后重试');
        }
      } else {
    
    
        throw Exception('网络请求失败');
      }
    }
  }

  // ...
}

In the above example, we first catch the Dio component's exception type DioError. Then according to different error types, we can customize the exception information and throw an exception.

This is just a simple example. You can further improve the error handling logic and define more exception types according to project requirements.


Summarize

By re-encapsulating the Flutter Dio components, we can improve code reusability and maintainability, and simplify the calling process of network requests. During the encapsulation process, we can add functions such as interceptors and error handling to make network requests more flexible and reliable.

I hope this document can help you understand how to repackage Flutter Dio components and apply them in actual projects. If you have more in-depth requirements for Dio components, it is recommended to refer to Dio official documentation for more detailed information.

Good luck with your Flutter development! If you have any questions, please feel free to ask.

Guess you like

Origin blog.csdn.net/u010755471/article/details/131409862