Flutter API服务调用插件md_api_service的使用

Flutter API服务调用插件md_api_service的使用

APIService 是一个用于Dart/Flutter项目的基类API服务库。该库主要受到 MGAPService 的启发。

感谢 tuan188

安装

在你的 pubspec.yaml 文件中添加 md_api_service 包:

dependencies:
  md_api_service: ^版本号

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

使用

example 目录下提供了简单的示例代码,展示了如何使用 md_api_service

示例代码

示例代码位于 这里

import 'package:md_api_service/api_service.dart';

// 导入必要的类和模型
import 'api_service.dart';
import 'inputs/api_input.dart';
import 'models/todo.dart';

void main(List<String> arguments) async {
  // 设置日志打印函数
  Log.logPrint = print;
  
  // 创建APIService实例
  final apiService = APIService();

  // 创建API输入对象
  final postTodoAPIInput = PostTodoAPIInput(todo: Todo(1, 1, 'abc', false));

  try {
    // 发起请求并处理响应
    final response = await apiService.requestJSONObject(
      postTodoAPIInput,
      mapper: Todo.fromJson,
      options: NetworkRequestOptions(
        printToCurl: true,
      ),
    );

    // 打印响应数据
    Log.json(response);
  } catch (error, stackTrace) {
    // 捕获异常并记录错误信息
    Log.e('', time: DateTime.now(), error: error, stackTrace: stackTrace);
  }
}

示例代码解释

  1. 导入必要的类和模型

    import 'api_service.dart';
    import 'inputs/api_input.dart';
    import 'models/todo.dart';
    
  2. 设置日志打印函数

    Log.logPrint = print;
    
  3. 创建APIService实例

    final apiService = APIService();
    
  4. 创建API输入对象

    final postTodoAPIInput = PostTodoAPIInput(todo: Todo(1, 1, 'abc', false));
    
  5. 发起请求并处理响应

    final response = await apiService.requestJSONObject(
      postTodoAPIInput,
      mapper: Todo.fromJson,
      options: NetworkRequestOptions(
        printToCurl: true,
      ),
    );
    
  6. 打印响应数据

    Log.json(response);
    
  7. 捕获异常并记录错误信息

    Log.e('', time: DateTime.now(), error: error, stackTrace: stackTrace);
    

更多关于Flutter API服务调用插件md_api_service的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter API服务调用插件md_api_service的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


md_api_service 是一个用于 Flutter 的 API 服务调用插件,它简化了与后端 API 的交互过程。通过这个插件,你可以轻松地进行 HTTP 请求,处理响应,并管理 API 调用的状态。

以下是 md_api_service 插件的基本使用方法:

1. 安装插件

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

dependencies:
  flutter:
    sdk: flutter
  md_api_service: ^1.0.0  # 请根据实际情况使用最新版本

然后运行 flutter pub get 来安装插件。

2. 初始化 API 服务

在使用 md_api_service 之前,你需要初始化一个 ApiService 实例。通常你可以在应用的入口文件(如 main.dart)中进行初始化。

import 'package:md_api_service/md_api_service.dart';

void main() {
  ApiService apiService = ApiService(
    baseUrl: 'https://your-api-base-url.com',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': 'Bearer your-access-token',
    },
  );

  runApp(MyApp(apiService: apiService));
}

3. 使用 ApiService 进行请求

你可以使用 ApiService 实例来执行 GET、POST、PUT、DELETE 等 HTTP 请求。

GET 请求示例

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

POST 请求示例

Future<void> postData() async {
  try {
    var response = await apiService.post(
      '/endpoint',
      body: {
        'key1': 'value1',
        'key2': 'value2',
      },
    );
    print('Response: $response');
  } catch (e) {
    print('Error: $e');
  }
}

PUT 请求示例

Future<void> putData() async {
  try {
    var response = await apiService.put(
      '/endpoint',
      body: {
        'key1': 'value1',
        'key2': 'value2',
      },
    );
    print('Response: $response');
  } catch (e) {
    print('Error: $e');
  }
}

DELETE 请求示例

Future<void> deleteData() async {
  try {
    var response = await apiService.delete('/endpoint');
    print('Response: $response');
  } catch (e) {
    print('Error: $e');
  }
}

4. 处理响应

ApiService 返回的响应通常是一个 Map<String, dynamic> 类型的对象,你可以根据需要解析和处理这些数据。

5. 错误处理

ApiService 会自动处理一些常见的错误(如网络错误、服务器错误等),并将错误信息抛出。你可以使用 try-catch 块来捕获和处理这些错误。

6. 自定义配置

你可以通过 ApiService 的构造函数传递自定义的配置,如超时时间、拦截器等。

ApiService apiService = ApiService(
  baseUrl: 'https://your-api-base-url.com',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer your-access-token',
  },
  timeout: Duration(seconds: 10),
  interceptors: [
    (request) {
      print('Request: $request');
      return request;
    },
    (response) {
      print('Response: $response');
      return response;
    },
  ],
);

7. 使用拦截器

拦截器允许你在请求发送前和响应接收后进行一些操作。你可以使用拦截器来记录日志、添加公共请求头等。

ApiService apiService = ApiService(
  baseUrl: 'https://your-api-base-url.com',
  interceptors: [
    (request) {
      print('Request: $request');
      request.headers['Custom-Header'] = 'CustomValue';
      return request;
    },
    (response) {
      print('Response: $response');
      return response;
    },
  ],
);

8. 处理文件上传

md_api_service 也支持文件上传。你可以使用 multipart/form-data 格式来上传文件。

Future<void> uploadFile() async {
  try {
    var response = await apiService.upload(
      '/upload-endpoint',
      files: {
        'file': await MultipartFile.fromFile('path/to/file.txt'),
      },
      fields: {
        'key1': 'value1',
      },
    );
    print('Response: $response');
  } catch (e) {
    print('Error: $e');
  }
}

9. 处理文件下载

你也可以使用 md_api_service 来下载文件。

Future<void> downloadFile() async {
  try {
    var response = await apiService.download(
      '/download-endpoint',
      savePath: 'path/to/save/file.txt',
    );
    print('Response: $response');
  } catch (e) {
    print('Error: $e');
  }
}
回到顶部