Flutter自定义网络请求插件custom_dio的使用

Flutter 自定义网络请求插件 custom_dio 的使用

在本教程中,我们将学习如何使用 custom_dio 插件来发送网络请求。custom_dio 是一个基于 Dio 的自定义封装,可以简化网络请求的过程。

初始化

首先,在发送任何请求之前,我们需要初始化 CustomDio

WidgetsFlutterBinding.ensureInitialized();
CustomDio.setInitData(
  CustomDioOptions(
    baseUrl: "http://www.example.com/api/v1/",
    headers: {"authorization": "Bearer xxx"},
  ),
);

发送 POST 请求

我们可以使用 CustomDio 发送 POST 请求:

try {
  final data = await CustomDio()
    .send(reqMethod: "post", path: "user/login", body: {"email": "email"});
} catch (err) {
  print(err.toString());
}

发送 GET 请求

我们也可以发送 GET 请求:

try {
  final data = await CustomDio()
    .send(reqMethod: "get", path: "user/login", query: {"search": "email"});
} catch (err) {
  print(err.toString());
}

上传文件

要上传文件,可以使用 uploadFile 方法:

try {
  final data = await CustomDio()
    .uploadFile(path: "path", filePath: File("").path, body: [
      {"one": "one"},
      {"two": "two"},
    ]);
} catch (err) {
  print(err.toString());
}

上传字节数据

要上传字节数据,可以使用 uploadBytes 方法:

try {
  final data = await CustomDio().uploadBytes(
    path: "dio-test/file",
    bytesExtension: "png",
    bytes: bytes,
    body: [
      {"content": "sd"},
      {"attachments": "attachments"},
    ],
  );
  
  return data.data.toString();
} catch (err) {
  rethrow;
}

发送 DELETE 请求

要发送 DELETE 请求,可以使用 send 方法并指定请求方法为 delete

Future delete() async {
  try {
    final data = await CustomDio().send(reqMethod: "delete", path: "dio-test/1");
    print(data.data.toString());
  } catch (err) {
    print(err.toString());
  }
}

获取单个资源

要获取单个资源,可以使用 send 方法并指定请求方法为 get

Future getOne() async {
  try {
    final data = await CustomDio().send(reqMethod: "get", path: "dio-test/154");
    print(data.data.toString());
  } catch (err) {
    print(err.toString());
  }
}

发送 PATCH 请求

要发送 PATCH 请求,可以使用 send 方法并指定请求方法为 patch

Future update() async {
  try {
    final data = await CustomDio().send(
      reqMethod: "patch",
      path: "dio-test",
      body: {"content": "update content"},
    );
    print(data.data.toString());
  } catch (err) {
    print(err.toString());
  }
}

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

1 回复

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


当然,下面是一个关于如何在Flutter项目中自定义网络请求插件custom_dio的示例代码。假设custom_dio是一个封装了dio库的自定义网络请求插件,用于简化API请求和错误处理。

1. 创建custom_dio插件

首先,我们需要创建一个Flutter插件项目,这里假设你已经有一个Flutter项目,现在创建一个名为custom_dio的插件。

Step 1: 创建插件

在Flutter项目根目录下运行:

flutter create --org com.example --template=plugin custom_dio

Step 2: 实现插件逻辑

进入custom_dio目录,编辑lib/custom_dio.dart文件,添加如下代码:

import 'package:dio/dio.dart';
import 'package:flutter/services.dart';

class CustomDio {
  static final Dio dio = Dio(
    BaseOptions(
      baseUrl: "https://api.example.com", // 替换为你的API基础URL
      connectTimeout: 5000,
      receiveTimeout: 30000,
      headers: {
        "Content-Type": "application/json",
      },
    )
  );

  // 封装GET请求
  static Future<Response<dynamic>> get(String path, {Map<String, dynamic>? queryParameters}) async {
    try {
      Response<dynamic> response = await dio.get(path, queryParameters: queryParameters);
      return response;
    } catch (e) {
      throw CustomDioException(e);
    }
  }

  // 封装POST请求
  static Future<Response<dynamic>> post(String path, Map<String, dynamic> data) async {
    try {
      Response<dynamic> response = await dio.post(path, data: data);
      return response;
    } catch (e) {
      throw CustomDioException(e);
    }
  }
}

// 自定义异常类
class CustomDioException implements Exception {
  String message;

  CustomDioException(dynamic error) {
    if (error is DioError) {
      DioError dioError = error;
      if (dioError.response != null) {
        message = "Error: ${dioError.response?.data['message'] ?? 'Unknown Error'} (${dioError.response?.statusCode})";
      } else {
        message = "Error: ${dioError.message} (${dioError.type})";
      }
    } else {
      message = error.toString();
    }
  }

  @override
  String toString() => message;
}

2. 在Flutter项目中使用custom_dio插件

Step 1: 添加插件依赖

回到你的Flutter项目根目录,编辑pubspec.yaml文件,添加custom_dio插件依赖:

dependencies:
  flutter:
    sdk: flutter
  custom_dio:
    path: ./custom_dio  # 使用本地路径引用插件

Step 2: 使用custom_dio进行网络请求

编辑你的Flutter应用中的某个Dart文件,比如lib/main.dart,添加如下代码:

import 'package:flutter/material.dart';
import 'package:custom_dio/custom_dio.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Custom Dio Example'),
        ),
        body: Center(
          child: FutureBuilder<Response<dynamic>>(
            future: fetchData(),
            builder: (context, snapshot) {
              if (snapshot.connectionState == ConnectionState.done) {
                if (snapshot.hasError) {
                  return Text('Error: ${snapshot.error}');
                } else {
                  // 假设API返回的数据是JSON格式
                  Map<String, dynamic> data = snapshot.data?.data as Map<String, dynamic>;
                  return Text('Data: ${data['key'] ?? 'No data'}');
                }
              } else {
                return CircularProgressIndicator();
              }
            },
          ),
        ),
      ),
    );
  }

  Future<Response<dynamic>> fetchData() async {
    try {
      return await CustomDio.get("/endpoint"); // 替换为你的API端点
    } catch (e) {
      throw e;
    }
  }
}

总结

以上代码展示了如何创建一个自定义网络请求插件custom_dio,并在Flutter项目中使用它进行网络请求。这个插件封装了dio库,简化了API请求和错误处理。你可以根据实际需求进一步扩展和优化这个插件。

回到顶部