Flutter基础客户端功能插件basic_client的使用

Flutter基础客户端功能插件basic_client的使用

基本客户端 (Basic Client)

一个支持多种HTTP方法和日志记录的基础Flutter网络客户端。

特性 (Features)

  • 支持GET、POST、PUT、PATCH、DELETE请求
  • JSON解析
  • 请求和响应的日志记录
  • 自定义头部和查询参数

安装 (Installation)

pubspec.yaml文件中添加以下依赖项:

dependencies:
    basic_client: ^1.0.0

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

使用 (Usage)

基础设置 (Basic Setup)

首先导入basic_client库,并创建一个BasicNetworkManager实例:

import 'package:basic_client/basic_client.dart';

void main() {
    final manager = BasicNetworkManager(
        baseUrl: 'https://jsonplaceholder.typicode.com',
        level: LogLevel.all,
    );

    // 使用管理器发起请求
}

发起请求 (Making Requests)

GET请求

final response = await manager.get<PostResponse, List<PostResponse>>(
    '/posts',
    response: PostResponse(),
);

if (response is BasicSuccess<List<PostResponse>>) {
    print('Posts: ${response.data}');
} else if (response is BasicFailure) {
    print('Error: ${response.errorMessage}');
}

POST请求

final request = PostRequest(
    userId: 24,
    title: 'foo',
    body: 'bar',
);
final response = await manager.post<PostResponse, PostResponse>(
    '/posts',
    response: PostResponse(),
    body: request.toJson(),
    headers: {
        'Content-type': 'application/json; charset=UTF-8',
    },
);

if (response is BasicSuccess<PostResponse>) {
    print('Created Post: ${response.data}');
} else if (response is BasicFailure) {
    print('Error: ${response.errorMessage}');
}

PUT请求

final request = PostRequest(
    userId: 24,
    title: 'foo',
    body: 'bar',
);
final response = await manager.put<PostResponse, PostResponse>(
    '/posts/1',
    response: PostResponse(),
    body: request.toJson(),
    headers: {
        'Content-type': 'application/json; charset=UTF-8',
    },
);

if (response is BasicSuccess<PostResponse>) {
    print('Updated Post: ${response.data}');
} else if (response is BasicFailure) {
    print('Error: ${response.errorMessage}');
}

PATCH请求

final request = PostRequest(
    title: 'foo',
);
final response = await manager.patch<PostResponse, PostResponse>(
    '/posts/1',
    response: PostResponse(),
    body: request.toJson(),
    headers: {
        'Content-type': 'application/json; charset=UTF-8',
    },
);

if (response is BasicSuccess<PostResponse>) {
    print('Patched Post: ${response.data}');
} else if (response is BasicFailure) {
    print('Error: ${response.errorMessage}');
}

DELETE请求

final response = await manager.delete<PostResponse, PostResponse>(
    '/posts/1',
    response: PostResponse(),
);

if (response is BasicSuccess<PostResponse>) {
    print('Deleted Post');
} else if (response is BasicFailure) {
    print('Error: ${response.errorMessage}');
}

更多关于Flutter基础客户端功能插件basic_client的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter基础客户端功能插件basic_client的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


basic_client 是一个用于 Flutter 的简单 HTTP 客户端插件,它提供了基本的 HTTP 请求功能,如 GET、POST、PUT、DELETE 等。这个插件通常用于需要与 RESTful API 进行交互的 Flutter 应用程序中。

安装 basic_client

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

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

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

使用 basic_client

以下是如何在 Flutter 应用中使用 basic_client 进行 HTTP 请求的示例。

1. 导入 basic_client

import 'package:basic_client/basic_client.dart';

2. 创建 BasicClient 实例

final client = BasicClient();

3. 发起 GET 请求

void fetchData() async {
  final response = await client.get('https://jsonplaceholder.typicode.com/posts/1');
  
  if (response.statusCode == 200) {
    print('Response data: ${response.body}');
  } else {
    print('Failed to load data');
  }
}

4. 发起 POST 请求

void postData() async {
  final response = await client.post(
    'https://jsonplaceholder.typicode.com/posts',
    body: {
      'title': 'foo',
      'body': 'bar',
      'userId': 1,
    },
  );
  
  if (response.statusCode == 201) {
    print('Response data: ${response.body}');
  } else {
    print('Failed to post data');
  }
}

5. 发起 PUT 请求

void updateData() async {
  final response = await client.put(
    'https://jsonplaceholder.typicode.com/posts/1',
    body: {
      'id': 1,
      'title': 'foo',
      'body': 'bar',
      'userId': 1,
    },
  );
  
  if (response.statusCode == 200) {
    print('Response data: ${response.body}');
  } else {
    print('Failed to update data');
  }
}

6. 发起 DELETE 请求

void deleteData() async {
  final response = await client.delete('https://jsonplaceholder.typicode.com/posts/1');
  
  if (response.statusCode == 200) {
    print('Data deleted successfully');
  } else {
    print('Failed to delete data');
  }
}

处理响应

BasicClient 的请求方法返回一个 Response 对象,你可以通过 response.statusCode 获取 HTTP 状态码,通过 response.body 获取响应体。

错误处理

在实际应用中,建议添加错误处理逻辑,例如:

void fetchData() async {
  try {
    final response = await client.get('https://jsonplaceholder.typicode.com/posts/1');
    
    if (response.statusCode == 200) {
      print('Response data: ${response.body}');
    } else {
      print('Failed to load data');
    }
  } catch (e) {
    print('Error: $e');
  }
}

自定义请求头

你可以在请求中添加自定义请求头:

void fetchDataWithHeaders() async {
  final response = await client.get(
    'https://jsonplaceholder.typicode.com/posts/1',
    headers: {
      'Authorization': 'Bearer your_token',
    },
  );
  
  if (response.statusCode == 200) {
    print('Response data: ${response.body}');
  } else {
    print('Failed to load data');
  }
}
回到顶部