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

패키지 상세v1.0.0

offline_sync

오프라인 우선 전략을 통해 데이터를 관리하고 동기화하도록 설계된 패키지로, 인터넷 연결 여부와 무관하게 원활한 기능을 보장하며 연결이 복원되면 자동으로 동기화됩니다.

AndroidiOSmacOS
30일 다운로드
20
좋아요
34
Pub 점수
120

패키지 설치

flutter pub add offline_sync

패키지 개요

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

offline_sync는 오프라인 우선 데이터 관리를 가능하게 하는 Flutter/Dart 패키지로, 인터넷 연결 없이도 앱이 원활하게 작동할 수 있도록 합니다. 데이터는 로컬에 저장되며 연결이 복원되면 변경 사항을 자동으로 동기화합니다. 신뢰성과 일관성을 위해 설계되었으며 Android, iOS, macOS 플랫폼에서 지속적인 스토리지를 지원합니다. 동기화 작업 중 데이터 무결성을 보장하기 위해 충돌 해결 및 상태 추적을 처리합니다. 최종적으로 일관된 강력한 로컬 데이터 처리가 필요한 애플리케이션에 적합합니다.

사용 사례

  • 오프라인 데이터 입력
  • 간헐적인 연결과 실시간 협업
  • 저연결 지역의 모바일 앱
  • 성능 향상을 위한 데이터 캐싱
  • 사용자 생성 콘텐츠의 동기화

주요 기능

  • 연결 복원 시 자동 동기화
  • 갈등 해결 전략
  • 지속적인 로컬 저장소
  • 크로스 플랫폼 지원 (Android, iOS, macOS)
  • 경량이며 쉽게 통합 가능

적합한 대상

  • 현장 서비스 애플리케이션
  • 오프라인 사용이 가능한 생산성 도구
  • 콘텐츠 생성 앱
  • 원격 또는 불안정한 네트워크 환경을 대상으로 하는 앱
  • 데이터 회복력을 우선시하는 개발자

고려 사항

  • 동기화 충돌을 신중하게 처리해야 합니다
  • 로컬 저장소 사용량이 증가할 수 있습니다
  • 초기 설정에서는 동기화 규칙을 정의해야 합니다
  • 실시간 동기화 업데이트에 적합하지 않습니다
  • 성능은 하위 데이터베이스 구현에 따라 달라집니다

원본 README

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

OfflineSync

OfflineSync is a Flutter package that provides offline-first data management and synchronization. It ensures smooth functionality even without an internet connection and syncs data once connectivity is restored.

Features

  • Local data storage and retrieval
  • Automatic synchronization with server when online
  • Conflict resolution
  • Encryption of sensitive data
  • Batch syncing for improved performance
  • Error handling and retry mechanisms

Installation

Add this to your package's pubspec.yaml file:

dependencies:
  offline_sync: ^1.0.0

Usage

Initialization

First, initialize the OfflineSync instance in your app:

import 'package:offline_sync/offline_sync.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  final offlineSync = OfflineSync(
    config: OfflineSyncConfig(
      apiEndpoint: 'https://your-custom-api.com',
      // encryptionKey is optional and will be generated automatically if not provided
    ),
  );
  await offlineSync.initialize();
  runApp(MyApp());
}

Setting Custom API Endpoint

Set a custom endpoint for your specific server:

final offlineSync = OfflineSync();
offlineSync.setApiEndpoint('https://your-custom-api.com');

Saving Data

To save data locally and queue it for syncing:

final offlineSync = OfflineSync();
await offlineSync.saveLocalData('user_1', {
  'name': 'John Doe',
  'email': 'john@example.com',
  'age': 30,
});

Reading Data

To read locally stored data:

final userData = await offlineSync.readLocalData('user_1');
if (userData != null) {
  print('User name: ${userData['name']}');
} else {
  print('User not found');
}

Syncing with Server

The package automatically syncs data when an internet connection is available. However, you can manually trigger a sync:

try {
  await offlineSync.updateFromServer();
  print('Data updated from server successfully');
} catch (e) {
  print('Failed to update from server: $e');
}

Handling Authentication

Set the authentication token for API requests:

await offlineSync.setAuthToken('your_auth_token_here');

Advanced Usage:

Conflict Resolution

The package includes basic conflict resolution. You can customize this by extending the OfflineSync class:

class CustomOfflineSync extends OfflineSync {
  @override
  Future<Map<String, dynamic>> resolveConflict(
    String id,
    Map<String, dynamic> localData,
    Map<String, dynamic> serverData
  ) async {
    // Implement your custom conflict resolution strategy here
    // This example prefers local changes
    final resolvedData = Map<String, dynamic>.from(serverData);
    localData.forEach((key, value) {
      if (value != serverData[key]) {
        resolvedData[key] = value;
      }
    });
    return resolvedData;
  }
}

Batch Processing

The package processes sync queue in batches. You can adjust the batch size:

class CustomOfflineSync extends OfflineSync {
  @override
  int get batchSize => 100; // Default is 50
}

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

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

Using with Flutter Provider

Wrap your app with the OfflineSyncProvider to make the sync instance and its status available throughout the widget tree:

final offlineSync = OfflineSync(config: OfflineSyncConfig(
  apiEndpoint: 'https://your-api.com',
  // encryptionKey is now optional
));
await offlineSync.initialize();

runApp(
  OfflineSyncProvider(
    offlineSync: offlineSync,
    child: MyApp(),
  ),
);

Then, anywhere in your widget tree, you can access the sync instance and status:

final offlineSync = OfflineSyncProvider.of(context);
ValueListenableBuilder<SyncStatus>(
  valueListenable: offlineSync.syncStatus,
  builder: (context, status, _) {
    // Show sync status in UI
    return Text('Sync status: $status');
  },
)

API Reference

OfflineSyncConfig
  • apiEndpoint (String, required): The server endpoint for syncing.
  • batchSize (int, default: 50): Number of items to sync per batch.
  • encryptionKey (String, optional): 32-character key for AES encryption. If not provided, a secure key is generated and stored automatically.
  • encryptionIV (IV, optional): Custom IV for encryption.
  • conflictResolver (callback, optional): Custom function for resolving data conflicts.
  • logger (callback, optional): Function for debug or error logging.
OfflineSync
  • OfflineSync({required OfflineSyncConfig config, ...}): Create a new instance with config and optional injected dependencies.
  • Future<void> initialize(): Initialize the database and connectivity.
  • Future<void> setAuthToken(String token): Set the auth token for API requests.
  • Future<void> saveLocalData(String id, Map<String, dynamic> data): Save data locally and queue for sync.
  • Future<Map<String, dynamic>?> readLocalData(String id): Read local data by ID.
  • Future<void> updateFromServer(): Manually trigger sync from server.
  • ValueNotifier<SyncStatus> syncStatus: Listen for sync status changes.
  • ValueNotifier<SyncErrorType?> lastError: Listen for error changes.
  • ValueNotifier<double> syncProgress: Listen for sync progress (0.0 to 1.0).

Migration Guide

From Singleton to Instance API
  • Before:
    final offlineSync = OfflineSync();
    await offlineSync.initialize();
    offlineSync.setApiEndpoint('https://api.com');
    
  • After:
    final offlineSync = OfflineSync(
      config: OfflineSyncConfig(
        apiEndpoint: 'https://api.com',
        // encryptionKey is now optional
      ),
    );
    await offlineSync.initialize();
    
  • Use the new OfflineSyncProvider to expose the instance to your widget tree.
  • Set all configuration options via OfflineSyncConfig instead of setters.

카테고리

의존성

의존성 목록 6 개

소스 저장소

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

아직 데이터가 없습니다.