搜尋套件、儲存庫與 APP 分類

套件詳情v3.0.1

http_services

一個基於 Dio 的 Dart 套件,提供基礎模型以處理 HTTP 服務請求。

AndroidiOSWebmacOSWindowsLinux
近 30 天下載
154
喜歡數
12
Pub 分數
160

安裝套件

flutter pub add http_services

套件介紹

根據套件公開資料產生的選型評估,僅供參考。

一個基於 Dio 建立的 Dart 套件,提供可重複使用的基礎模型來管理 HTTP 服務請求。它透過提供一致的結構、錯誤處理以及請求/回應抽象,簡化了網路操作的實作。非常適合尋求在多個平台以簡化方式整合 API 的開發者。此套件支援 Android、iOS、Web、macOS、Windows 與 Linux,確保跨平台相容性。它提升程式碼可維護性,並減少使用 RESTful API 時的重複程式碼。

適用情境

  • 構建 RESTful API 客戶端
  • 處理經過驗證的請求
  • 集中化 HTTP 邏輯
  • 管理 API 回應解析
  • 實施重試機制
  • 標準化錯誤處理

主要特色

  • 基礎請求/回應模型
  • 基於 Dio 建構以實現高效能
  • 跨平台支援
  • 一致的錯誤處理
  • 可擴展的設計
  • 與現有項目的輕鬆整合

適合對象

  • 使用 Dio 的開發者
  • 需要標準化HTTP呼叫的項目
  • 希望擁有可重用的 HTTP 模式
  • 針對多個平台的應用
  • API密集型應用

使用建議

  • 需要熟悉 Dio
  • 僅限HTTP服務使用情境
  • 可能需要額外設定以應對複雜情境
  • 不適用於非HTTP網路任務

原始 README

以下為關聯原始碼儲存庫的 README 原文快照,最新內容請造訪原始碼儲存庫。

http_services

A package to support the creation of Http services in a Dart application.

Features

  • convenient methods to perform HTTP requests
  • disposing a service will cleanup any pending requests, in order to avoid unwanted resources waste!
  • convenient models to have a standard for request and response objects

RequestBase

Every request should extend RequestBase and implement its overrides:

  • endpoint: Specify the path of the request
  • toJson: This method is used for the request's serialization
  • toData: This is an optional override in case you need to post a non JSON body. It returns an object of type T.

By default toData returns null

ResponseBase

Every response should extend ResponseBase

Exceptions

All the exceptions of this package extend HttpServiceException

ApiException:

This is thrown when something is wrong with the request (e.g. missing internet, resource not found, etc).

  • networkError signals if there was an outage in connection
  • httpCode is the received HTTP status code
  • httpMessage is the received HTTP status message
UnexpectedStatusCodeException:

This is thrown when expected HTTP code doesn't match the received one.

  • expected is the expected status code
  • actual is the received status code
ResponseMappingException:

This is thrown when an error occurs while mapping the response.

RequestCanceledException:

This is thrown when a request is canceled.

HttpServiceBase

Every service should extend this.

To make a request within you service, you can use one of the following:

  • getQuery: perform a GET request
  • postData: perform a POST request
  • postJson: perform a POST request with a JSON body
  • putData: perform a PUT request
  • putJson: perform a PUT request with a JSON body
  • deleteData: perform a DELETE request
  • deleteJson: perform a DELETE request with a JSON body
  • patchData: perform a PATCH request
  • patchJson: perform a PATCH request with a JSON body
  • download: downloads a file
  • getBytes: gets bytes from an endpoint

Example

import 'package:dio/dio.dart';
import 'package:http_services/http_services.dart';

import 'todos_service.dart';


class TodosRequest extends RequestBase {
  final int page;

  TodosRequest(this.page) : assert(page != null && page > 0);
  @override
  String get endpoint => '/todos/$page';

  @override
  Map<String, dynamic> toJson() {
    return {};
  }
}


class TodosResponse extends ResponseBase {
  final int userId;
  final int id;
  final String title;
  final bool completed;

  TodosResponse({
    this.userId,
    this.id,
    this.title,
    this.completed,
  });

  factory TodosResponse.fromJson(Map<String, dynamic> json) => TodosResponse(
        userId: json['userId'],
        id: json['id'],
        title: json['title'],
        completed: json['completed'],
      );
}


class TodosService extends HttpServiceBase {
  TodosService(Dio dioInstance) : super(dioInstance);

  Future<TodosResponse> getTodo(int page) {
    final request = TodosRequest(page);

    return getQuery(
      request: request,
      mapper: (json, _) => TodosResponse.fromJson(json),
    );
  }
}

void main() async {
  final dio = Dio(
    BaseOptions(
      baseUrl: 'https://jsonplaceholder.typicode.com/',
    ),
  );

  final service = TodosService(dio);

  try {
    print("Requesting data...");
    final response1 = await service.getTodo(1);
    print(
      "user id: ${response1.userId}\n"
      "id: ${response1.id}\n"
      "title: ${response1.title}\n"
      "completed: ${response1.completed}",
    );
  } on HttpServiceException catch (e) {
    print('Service exception: ${e.runtimeType}');
  }
}

Notes

There might be some cases where the JSON response is not like this:

{
  "data": [{"name": "Bob"},{"name":"Alice"}],
}

This will not be treated as a JSON since it's not a Map<String,dynamic> but it's a List<Map<String,dynamic>>. A solution might be to use the orElse parameter when performing the HTTP request. Remember that orElse is executed to map any response body that's not Map<String,dynamic>.

Similarly, if you ever find yourself in need of sending a JSON like the one above, a solution might be to override the onData method of RequestBase in your request object and then using the *data version of the request. For example:


class User{
  final String name;
  User(this.name);

  Map<String,dynamic> toJson() => {'name': name};
}

class UsersToSend extends RequestBase{
  final List<User> users;
  UsersToSend(this.users);

  @override
  Map<String,dynamic> toJson() => {};

  @override
  List<User> toData() => users;
}

and then use postData instead of using postJson in your service.

Contributors 🚀

所屬分類

依賴

依賴清單 3 項

  • dio^5.5.0+1
  • disposable_object^2.0.0
  • meta^1.3.0

原始碼儲存庫

使用此套件的專案

暫無相關資料。