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

패키지 상세v0.2.1

jh_services

Flutter용 가벼운 서비스 패키지로 네트워크 요청, 로컬 저장소 및 연결성을 최상의 실천 방법을 따르며 원활하게 처리합니다.

AndroidiOSWebmacOSWindowsLinux
30일 다운로드
714
좋아요
2
Pub 점수
160

패키지 설치

flutter pub add jh_services

패키지 개요

공개 정보를 바탕으로 생성한 선택 가이드입니다.

jh_services는 최선의 실천 방법을 사용하여 네트워크 요청, 로컬 저장소 관리 및 연결성 확인을 간소화하는 가벼운 Flutter 패키지입니다. HTTP 작업 처리, 로컬 데이터 캐싱, 그리고 다양한 플랫폼 간 장치 연결 상태 모니터링을 위한 통합적이고 사용하기 쉬운 인터페이스를 제공합니다. 단순함과 신뢰성을 중시하여 뼈대 코드를 줄이고 개발 생산성을 향상시킵니다. Android, iOS, Web, macOS, Windows, Linux 등 모든 주요 플랫폼을 지원하며, 강력한 백엔드 통합과 오프라인 기능이 필요한 크로스플랫폼 애플리케이션에 이상적입니다.

사용 사례

  • REST API 호출 처리
  • 로컬 데이터 지속성 관리
  • 인터넷 연결 모니터링
  • 오프라인 우선 기능 구현
  • 서비스 계층 로직 간소화
  • 크로스 플랫폼 데이터 동기화

주요 기능

  • 통합 서비스 인터페이스
  • 내장형 연결성 모니터링
  • 안전한 로컬 저장소
  • 자동 재시도 메커니즘
  • 플랫폼 독립적 설계
  • 최소한의 보일러플레이트

적합한 대상

  • 간단한 서비스 추상화를 찾는 Flutter 개발자
  • 오프라인 지원이 필요한 프로젝트
  • 자주 네트워크 상호작용을 하는 앱
  • 크로스플랫폼 모바일 및 데스크톱 앱
  • 유지보수 가능한 코드 구조를 우선시하는 팀

고려 사항

  • async/await 패턴에 대한 이해가 필요합니다
  • 고급 네트워킹 요구 사항을 위한 제한된 사용자 정의
  • 기본 HTTP 클라이언트 구현에 따라 다름
  • 매우 복잡한 API 워크플로우에는 적합하지 않습니다
  • 중규모 애플리케이션에 최적
  • 생산 환경 사용을 위해 추가적인 오류 처리가 필요할 수 있습니다

원본 README

연결된 소스 저장소의 README 원문 스냅샷입니다. 최신 내용은 저장소에서 확인하세요.

jh_services 0.1.1

jh_services is a Flutter package that provides a collection of services for handling common tasks in your Flutter applications, such as shared preferences, network requests, image and file picking, and checking internet connectivity.

Features

  • Shared Preferences Service: Manage local storage using shared preferences.
  • Network Service: Handle network requests with customizable configurations.
  • Image Picker Service: Pick images from the device's gallery or camera.
  • File Picker Service: Select files from the device's file system.
  • Connectivity Service: Check internet connectivity status and listen for changes.

Installation

Add jh_services to your pubspec.yaml file:

dependencies:
  jh_services: ^0.1.1

Usage

1. Setup Service Locator

Before using any of the services, you need to set up the service locator in your Flutter application. You can do this in your main.dart file:

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

void main() {
   setupServiceLocator(
    sharedPrefsConfig:SharedPrefsConfig() ,
    connectivityConfig: ConnectivityConfig(),
    networkConfig: NetworkConfig(baseUrl: 'https://api.example.com',
     defaultHeaders:  {
      'Content-Type': 'application/json',
      // Other headers if necessary
    },),
  );
  
  runApp(MyApp());
}
2. Initialize Services

You should initialize the services before using them. This is typically done in your main.dart file after setting up the service locator:

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();

  setupServiceLocator(
    sharedPrefsConfig:SharedPrefsConfig() ,
    connectivityConfig: ConnectivityConfig(),
    networkConfig: NetworkConfig(baseUrl: 'https://api.example.com',
     defaultHeaders:  {
      'Content-Type': 'application/json',
      // Other headers if necessary
    },),
  );
  runApp(MyApp());
}
3. Using the Services
Shared Preferences Service
import 'package:jh_services/jh_services.dart';

final sharedPrefsService = serviceLocator<SharedPrefsService>();

// Example of saving a value
await sharedPrefsService.saveString('key', 'value');

// Example of retrieving a value
String? value = sharedPrefsService.getString('key');
  • New Methods:
    • saveString(String key, String value): Save a string value under a specific key.
    • getString(String key): Retrieve a string value by key.
    • saveDateTime(String key, DateTime value): Save a DateTime value as a string.
    • getDateTime(String key): Retrieve a DateTime value.
    • updateOrAppendToStringList(String key, List<String> newList): Update a string list by replacing it if it exists or appending if it doesn't.
    • saveBulk(Map<String, dynamic> data): Save multiple key-value pairs in one go.
    • getBulk(List<String> keys): Retrieve multiple values for a list of keys.
    • removeBulk(List<String> keys): Remove multiple keys.
    • incrementOrInitInt(String key, {int incrementBy = 1, int initialValue = 0}): Increment or initialize an integer value.
    • decrementInt(String key, {int decrementBy = 1}): Decrement an integer value.
    • toggleBool(String key): Toggle a boolean value.
    • addToStringList(String key, String value): Add a single item to a list of strings.
    • removeFromStringList(String key, String value): Remove a single item from a list of strings.
    • getAll(): Retrieve all key-value pairs.
    • saveJson(String key, Map<String, dynamic> json): Save a JSON object by encoding it as a string.
    • getJson(String key): Retrieve a JSON object by decoding a stored string.
    • resetToDefaults(Map<String, dynamic> defaultValues): Reset a list of keys to specified default values.
    • getKeysByPrefix(String prefix): Retrieve all keys that start with a specified prefix.
    • getItemCount(): Count the number of stored items.
    • batchIncrementInts(Map<String, int> increments): Batch update to increment multiple integer keys by specified values.
    • retrieveAndRemove(List<String> keys): Retrieve and remove values for a list of keys.
    • getValue<T>(String key): Retrieve a value by type.
    • getKeys(): Retrieve all keys.
    • clear(): Clear all values.
    • containsKey(String key): Check if a key exists.
    • remove(String key): Remove a value associated with a specific key.
Network Service
import 'package:jh_services/jh_services.dart';

final networkService = serviceLocator<NetworkService>();

// Example of making a GET request
final response = await networkService.get('/endpoint');

// Example of making a POST request
final postResponse = await networkService.post('/endpoint', data: {'key': 'value'});

// Making a POST request with FormData
final formDataResponse = await networkService.post(
  '/upload',
  data: {
    'file': await convertImageToMultipartFile(image), // Example of using FormData
  },
  isFormData: true,
);

Exception Handling in jh_services

The jh_services package provides a robust error-handling mechanism when making network requests using Dio. Each type of network error throws a ServerException, which contains details such as an error message, the specific error type, and a status code.

Error Handling

The following table outlines the status codes returned for each DioExceptionType in case of an error:

Dio Exception Type Status Code Description
DioExceptionType.connectionTimeout 408 The request timed out while connecting to the server.
DioExceptionType.sendTimeout 504 The request timed out while sending data to the server.
DioExceptionType.receiveTimeout 504 The request timed out while receiving data from the server.
DioExceptionType.badCertificate 495 The SSL certificate is invalid.
DioExceptionType.cancel 499 The client canceled the request.
DioExceptionType.connectionError 503 There was a network connection error.
DioExceptionType.unknown 520 An unknown error occurred.
DioExceptionType.badResponse Varies Depends on the status code from the server (e.g., 400, 401, 403, 404, 409, 422, 504).
Example of Handling Exceptions

When you make a network request and an error occurs, a ServerException is thrown, which you can catch and process as follows:

try {
  final response = await networkService.get('/endpoint');
  print(response);
} on ServerException catch (e) {
  // Handle the exception
  print('Error: ${e.errorModel.message}');
  print('Status Code: ${e.errorModel.statusCode}');
}
Image Picker Service
import 'package:jh_services/jh_services.dart';

final imagePickerService = serviceLocator<ImagePickerService>();

// Example of picking an image
final imagePath = await imagePickerService.pickImage();
File Picker Service
import 'package:jh_services/jh_services.dart';

final filePickerService = serviceLocator<FilePickerService>();

// Example of picking a single file
final filePath = await filePickerService.pickSingleFile(allowedExtensions: ['pdf', 'docx']);

// Example of picking multiple files
final filePaths = await filePickerService.pickMultipleFiles();
Connectivity Service
import 'package:jh_services/jh_services.dart';

final connectivityService = serviceLocator<ConnectivityService>();

// Example of checking current connectivity status
final isConnected = await connectivityService.isConnected();


License

This project is licensed under the MIT License. See the LICENSE file for details.

카테고리

의존성

의존성 목록 6 개

소스 저장소

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

아직 데이터가 없습니다.