MC_DIO

Pub package Dio

简体中文 · English · 使用示例 / Usage

简体中文

项目简介

MC_DIO 是一个基于 Dio 的 Flutter 网络请求库。它采用命令模式,将每个 API 请求封装成独立对象,让请求地址、参数、请求方式、超时配置和回调逻辑保持清晰、集中且易于复用。

1.0.0 是首个正式版本,已适配 Dio 5.10.0,适合需要对象化请求、统一网络配置、批量请求和请求生命周期扩展能力的 Flutter 项目。

核心功能

  • 将每个 API 封装为独立的 MCBaseRequest 对象
  • 统一配置服务地址和请求日志
  • 支持 GET、POST、HEAD、PUT、DELETE、PATCH 和文件下载
  • 支持成功/失败回调与代理回调
  • 支持上传和下载进度回调
  • 支持请求生命周期附件 MCRequestAccessory
  • 支持多个请求并行执行和结果汇总
  • 请求配置相互隔离,同时复用底层连接池
  • 支持 Mock 数据,无需发起真实网络请求
  • 直接导出 Dio 类型,方便使用 FormDataCancelToken 和自定义拦截器

环境要求

  • Dart >=2.18.0 <4.0.0
  • Flutter
  • Dio ^5.10.0

English

Overview

MC_DIO is an object-oriented Flutter networking library built on Dio. It follows the Command pattern and represents every API call as a dedicated request object, keeping URLs, parameters, HTTP methods, timeout settings, and callbacks organized and reusable.

Version 1.0.0 is the first stable release and is compatible with Dio 5.10.0. It is designed for Flutter applications that need structured request objects, centralized configuration, batch execution, and extensible request lifecycle hooks.

Features

  • Encapsulates every API call in an independent MCBaseRequest object
  • Centralized base URL and request logging configuration
  • GET, POST, HEAD, PUT, DELETE, PATCH, and download support
  • Success/failure callbacks and delegate callbacks
  • Upload and download progress callbacks
  • Extensible request lifecycle hooks through MCRequestAccessory
  • Parallel batch requests with aggregated results
  • Isolated request configuration with shared connection reuse
  • Built-in mock responses without real network traffic
  • Re-exports Dio types for FormData, CancelToken, and custom interceptors

Requirements

  • Dart >=2.18.0 <4.0.0
  • Flutter
  • Dio ^5.10.0

安装 / Installation

在项目的 pubspec.yaml 中添加依赖:

Add MC_DIO to your project's pubspec.yaml:

dependencies:
  mc_dio: ^1.0.0

然后获取依赖:

Then install the dependency:

flutter pub get

连接复用与配置隔离 / Connection reuse and isolation

MC_DIO 为每个请求创建独立的 Dio 克隆,因此 Header、鉴权、超时和拦截器不会相互影响。这些克隆共享同一个 HttpClientAdapter,访问相同服务器时可以复用底层连接。

MC_DIO creates an isolated Dio clone for every request, so headers, authentication, timeouts, and interceptors cannot leak between requests. The clones share one HttpClientAdapter, allowing connections to be reused when requests target the same server.

Request A -> Scoped Dio A --\
Request B -> Scoped Dio B ----> Shared HttpClientAdapter
Request C -> Scoped Dio C --/

不要对请求对象的 dio 调用 close(),因为所有请求共享它的传输层。只有在应用不再使用网络层时,才统一关闭引擎:

Do not call close() on a request's dio, because its transport is shared. Close the engine only when the application no longer needs the network layer:

MCDioEngine.shared.close();

使用示例 / Usage

1. 全局配置 / Global configuration

建议在应用启动时配置服务地址和日志开关:

Configure the base URL and logging when the application starts:

import 'package:mc_dio/mc_dio.dart';

void configureNetwork() {
  MCNetworkConfig().baseUrl = 'https://api.example.com/';
  MCNetworkConfig().isLog = true;
}

2. 定义请求对象 / Define a request

每个接口对应一个请求类,通过覆写方法描述请求行为:

Create one request class for each API and override the methods that describe its behavior:

import 'package:mc_dio/mc_dio.dart';

class LoginRequest extends MCBaseRequest<LoginRequest> {
  LoginRequest({required this.username, required this.password});

  final String username;
  final String password;

  @override
  String requestUrl() => 'user/login';

  @override
  MCRequestMethod requestMethod() => MCRequestMethod.Post;

  @override
  Map<String, dynamic> requestArgument() => {
        'username': username,
        'password': password,
      };

  @override
  String contentType() => Headers.jsonContentType;

  @override
  ResponseType responseType() => ResponseType.json;
}

requestUrl() 可以返回相对路径,也可以直接返回完整的 HTTP/HTTPS 地址。

requestUrl() can return either a relative path or a complete HTTP/HTTPS URL.

3. 发送请求 / Send a request

final request = LoginRequest(
  username: 'demo',
  password: 'password',
);

request.startWithCompletionBlockWithSuccess(
  (data) {
    print('Success: ${data.response?.data}');
  },
  (data) {
    print('Failed: ${data.error?.message}');
  },
);

也可以通过 MCRequestDelegate 统一接收请求结果。

You can also implement MCRequestDelegate to receive request results through a delegate.

4. 监听进度 / Track progress

request.onSendProgress = (sent, total) {
  print('Upload: $sent / $total');
};

request.onReceiveProgress = (received, total) {
  print('Download: $received / $total');
};

5. 取消请求 / Cancel a request

request.stop();

取消后,失败回调会收到 DioExceptionType.cancel 类型的异常。

After cancellation, the failure callback receives a DioException with the DioExceptionType.cancel type.

6. 批量请求 / Batch requests

MCBatchRequest 可以并行执行多个请求,并分别汇总成功和失败结果:

MCBatchRequest executes multiple requests in parallel and aggregates successful and failed results:

final batchRequest = MCBatchRequest([
  LoginRequest(username: 'user-1', password: 'password-1'),
  LoginRequest(username: 'user-2', password: 'password-2'),
]);

batchRequest.startWithCompletionBlockWithSuccess((success, failure) {
  print('Success count: ${success.length}');
  print('Failure count: ${failure.length}');
});

7. 请求生命周期附件 / Request lifecycle accessories

附件适合处理 Loading、埋点或统一的请求状态通知。

Accessories are useful for loading indicators, analytics, and centralized request state notifications.

class LoadingAccessory implements MCRequestAccessory {
  @override
  void requestWillStart({
    RequestOptions? options,
    RequestInterceptorHandler? handler,
  }) {
    print('Request started');
  }

  @override
  void requestDidStop({
    Response? response,
    ResponseInterceptorHandler? handler,
    DioException? err,
    ErrorInterceptorHandler? handlerErr,
  }) {
    print('Request finished');
  }
}

request.addAccessory(LoadingAccessory());

8. Mock 数据 / Mock responses

覆写 mock() 并返回非空数据后,请求会直接返回该数据,不会访问网络。

Override mock() and return non-null data to complete the request without network traffic.

@override
Future<Map<String, dynamic>> mock() async {
  return {
    'token': 'mock-token',
    'user': {'id': 1, 'name': 'Demo'},
  };
}

常用覆写方法 / Common overrides

Method 中文说明 English description Default
requestUrl() 请求地址或相对路径 Request URL or relative path null
baseUrl() 服务基础地址 Service base URL MCNetworkConfig().baseUrl
requestMethod() HTTP 请求方法 HTTP method GET
requestArgument() 请求参数或请求体 Request parameters or body null
setHeader() 请求头 Request headers {}
connectTimeout() 连接超时,单位毫秒 Connection timeout in milliseconds 60000
sendTimeout() 发送超时,单位毫秒 Send timeout in milliseconds 60000
receiveTimeout() 接收超时,单位毫秒 Receive timeout in milliseconds 60000
contentType() 请求内容类型 Request content type Form URL encoded
responseType() 响应解析类型 Response parsing type plain
isLog() 是否输出请求日志 Whether to print request logs Global setting
mock() Mock 响应数据 Mock response data null

License

MC_DIO is available under the Anti 996 License.