패키지, 저장소 및 앱 카테고리 검색

패키지 상세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

소스 저장소

이 패키지를 사용하는 프로젝트

아직 데이터가 없습니다.