Flutter Offline Sync

A Flutter package for offline data synchronization. This package enables seamless data sync between local storage and a remote server, ensuring smooth functionality even in offline mode.

Features

  • Automatic sync when the internet is available
  • Local storage using Hive
  • Background data synchronization
  • Connectivity-aware sync mechanism

Installation

Add the package to your pubspec.yaml:

dependencies:
  flutter:
    sdk: flutter
  connectivity_plus: ^5.0.2
  hive: ^2.2.3
  hive_flutter: ^1.1.0

Run:

flutter pub get

Usage

1. Initialize Sync Manager

In your main.dart, initialize the sync manager:

import 'package:flutter/material.dart';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter_offline_data_sync/sync_manager.dart';
import 'package:hive_flutter/hive_flutter.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Hive.initFlutter();
  final syncManager = SyncManager();
  await syncManager.init();

  Connectivity().onConnectivityChanged.listen((event) {
    if (event != ConnectivityResult.none) {
      syncManager.syncData();
    }
  });

  runApp(MyApp());
}

2. Implement SyncManager

Create a SyncManager class to handle offline data storage and sync:

import 'package:hive/hive.dart';
import 'package:connectivity_plus/connectivity_plus.dart';

/// Manages offline data synchronization and local storage.
class SyncManager {
  late Box _box;

  /// Initializes the sync manager by opening the Hive box.
  Future<void> init() async {
    _box = await Hive.openBox('offline_data');
  }

  /// Saves data locally with a given [key] and [value].
  void saveData(String key, dynamic value) {
    _box.put(key, value);
  }

  /// Synchronizes local data with the remote server when online.
  Future<void> syncData() async {
    if (await Connectivity().checkConnectivity() != ConnectivityResult.none) {
      var offlineData = _box.toMap();
      // Send data to the server
      print("Syncing data: \$offlineData");
      _box.clear();
    }
  }
}

3. Store and Sync Data

Save data locally when offline and sync when online:

final syncManager = SyncManager();
/// Stores user data locally.
syncManager.saveData('user', {'name': 'John Doe', 'age': 25});

Running Tests

To run tests, execute:

flutter test

Example Project

Check out the /example folder for a complete working example.

Contributing

Contributions are welcome! Feel free to open an issue or submit a pull request.

License

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

Libraries

flutter_offline_data_sync
The main library for Flutter Offline Sync package.