Flutter网络请求插件dio_request_plus的使用

Flutter网络请求插件dio_request_plus的使用

在本教程中,我们将详细介绍如何使用 dio_request_plus 插件来处理网络请求。该插件提供了丰富的功能来简化网络请求的过程。

目录结构

|— client # 基础Http总线封装 |— handle # 处理场景值的处理者 |— interceptor # 通用拦截器 |— model # 通用数据模型


### 完整示例Demo

以下是一个完整的示例,展示了如何使用 `dio_request_plus` 插件进行网络请求。

#### 示例代码

```dart
import 'package:dio_request_plus/dio_request_plus.dart';
import 'package:flutter/material.dart';
import 'package:logger/logger.dart';

// 绑定网络请求的混入类
mixin HttpBinding on State<MyHomePage> {
  // 初始化网络请求配置
  void init() {
    HttpManager.instance.init(
      options: BaseOptions(
        receiveTimeout: 20 * 1000,
        connectTimeout: 20 * 1000,
        sendTimeout: 20 * 1000,
        contentType: Headers.formUrlEncodedContentType,
        responseType: ResponseType.json,
      ),
      enableCache: true,
      logger: Logger(),
      isDebug: true,
    );

    // 创建一个Dio实例
    final dio = HttpImplBuildTool().initDio(
      BaseOptions(
        receiveTimeout: 20 * 1000,
        connectTimeout: 20 * 1000,
        sendTimeout: 20 * 1000,
        contentType: Headers.formUrlEncodedContentType,
        responseType: ResponseType.json,
      ),
    );
  }
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  [@override](/user/override)
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> with HttpBinding {
  int _counter = 0;

  [@override](/user/override)
  void initState() {
    super.initState();
    init(); // 初始化网络请求
  }

  // 网络请求方法
  void fetchData() async {
    // 发起GET请求
    final response = await HttpManager.instance.request(
      '/your-api-endpoint',
      method: Method.GET,
    );

    if (response.isSuccess) {
      // 请求成功,处理响应数据
      print('Response data: ${response.data}');
    } else {
      // 请求失败,处理错误信息
      print('Error: ${response.error}');
    }
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: fetchData, // 调用网络请求方法
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ),
    );
  }
}

更多关于Flutter网络请求插件dio_request_plus的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter网络请求插件dio_request_plus的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


dio_request_plus 是一个基于 dio 的 Flutter 网络请求插件,它简化了 dio 的使用,并提供了更多的功能和便捷的配置选项。dio 是一个强大的 Dart HTTP 客户端,支持拦截器、全局配置、FormData、文件上传下载等。

以下是如何使用 dio_request_plus 插件的基本步骤:

1. 添加依赖

首先,你需要在 pubspec.yaml 文件中添加 dio_request_plus 依赖:

dependencies:
  flutter:
    sdk: flutter
  dio_request_plus: ^1.0.0  # 请使用最新版本

然后运行 flutter pub get 来安装依赖。

2. 导入包

在你的 Dart 文件中导入 dio_request_plus 包:

import 'package:dio_request_plus/dio_request_plus.dart';

3. 创建 Dio 实例

你可以通过 DioRequestPlus 创建一个 Dio 实例,并对其进行配置:

Dio dio = DioRequestPlus.createDio(
  baseUrl: 'https://jsonplaceholder.typicode.com', // 基础URL
  connectTimeout: 5000, // 连接超时时间
  receiveTimeout: 3000, // 接收超时时间
);

4. 发起网络请求

使用 Dio 实例发起 GET、POST 等请求:

GET 请求

Future<void> fetchData() async {
  try {
    Response response = await dio.get('/posts');
    print(response.data);
  } catch (e) {
    print('Error: $e');
  }
}

POST 请求

Future<void> postData() async {
  try {
    Response response = await dio.post(
      '/posts',
      data: {
        'title': 'foo',
        'body': 'bar',
        'userId': 1,
      },
    );
    print(response.data);
  } catch (e) {
    print('Error: $e');
  }
}

5. 使用拦截器

dio_request_plus 提供了拦截器功能,你可以在请求发送前或响应返回后进行一些处理:

dio.interceptors.add(
  InterceptorsWrapper(
    onRequest: (RequestOptions options, RequestInterceptorHandler handler) {
      // 在请求发送前做一些处理,比如添加 token
      options.headers['Authorization'] = 'Bearer your_token';
      return handler.next(options);
    },
    onResponse: (Response response, ResponseInterceptorHandler handler) {
      // 在响应返回后做一些处理
      return handler.next(response);
    },
    onError: (DioException e, ErrorInterceptorHandler handler) {
      // 在请求出错时做一些处理
      return handler.next(e);
    },
  ),
);

6. 文件上传

dio_request_plus 也支持文件上传功能:

Future<void> uploadFile() async {
  FormData formData = FormData.fromMap({
    'file': await MultipartFile.fromFile('path/to/your/file.txt', filename: 'file.txt'),
  });

  try {
    Response response = await dio.post('/upload', data: formData);
    print(response.data);
  } catch (e) {
    print('Error: $e');
  }
}

7. 文件下载

dio_request_plus 也支持文件下载功能:

Future<void> downloadFile() async {
  try {
    Response response = await dio.download(
      'https://example.com/file.zip',
      'path/to/save/file.zip',
    );
    print('File downloaded');
  } catch (e) {
    print('Error: $e');
  }
}

8. 取消请求

你可以通过 CancelToken 来取消请求:

CancelToken cancelToken = CancelToken();

Future<void> fetchDataWithCancel() async {
  try {
    Response response = await dio.get(
      '/posts',
      cancelToken: cancelToken,
    );
    print(response.data);
  } catch (e) {
    if (CancelToken.isCancel(e)) {
      print('Request canceled');
    } else {
      print('Error: $e');
    }
  }
}

// 取消请求
cancelToken.cancel();

9. 其他配置

你还可以通过 DioRequestPlus 进行其他配置,比如设置全局的 baseUrlheaderstimeout 等。

DioRequestPlus.configure(
  baseUrl: 'https://jsonplaceholder.typicode.com',
  headers: {
    'Authorization': 'Bearer your_token',
  },
  connectTimeout: 5000,
  receiveTimeout: 3000,
);
回到顶部