Skip to content

Latest commit

Β 

History

1 Commit

Folders and files

NameName
Last commit message
Last commit date
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Offline Sync Flutter App

A Flutter application demonstrating offline-first architecture with automatic cloud synchronization using Firebase Realtime Database, Hive local storage, and connectivity monitoring.

πŸš€ Features

  • βœ… Offline-First Architecture - All operations work without internet connection
  • βœ… Automatic Cloud Sync - Syncs to Firebase when online
  • βœ… Local Storage - Uses Hive for fast local data persistence
  • βœ… Real-time Connectivity Detection - Monitors network status with visual indicator
  • βœ… Sync Status Indicators - Shows whether notes are synced, local-only, or cloud-only
  • βœ… Manual Sync Control - Force sync or refresh data on demand
  • βœ… CRUD Operations - Create, read, update, and delete notes
  • βœ… Conflict Resolution - Handles sync conflicts with CRDT-based operations

πŸ“¦ Dependencies

dependencies:
  flutter: sdk: flutter
  offline_sync_engine: ^2.4.0    # Sync engine with CRDT support
  hive: ^2.2.3                   # Local NoSQL database
  hive_flutter: ^1.1.0           # Hive Flutter integration
  firebase_core: ^4.4.0          # Firebase initialization
  firebase_database: ^12.1.3     # Firebase Realtime Database
  connectivity_plus: ^7.0.0      # Network connectivity monitoring
  uuid: ^4.5.2                   # UUID generation

πŸ—οΈ Architecture

Components

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚   Flutter UI    β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”˜
         β”‚
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  SyncService    β”‚ (Singleton managing sync operations)
β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”˜
         β”‚
    β”Œβ”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”
    β”‚          β”‚
β”Œβ”€β”€β”€β–Όβ”€β”€β”€β”  β”Œβ”€β”€β”€β–Όβ”€β”€β”€β”€β”
β”‚  Hive β”‚  β”‚Firebaseβ”‚
β”‚ Local β”‚  β”‚ Cloud  β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”˜  β””β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Key Files

  • lib/main.dart - UI and user interactions
  • lib/sync.dart - Sync service managing local/cloud operations
  • lib/model.dart - Data models (Note, NoteView, NoteSyncStatus)
  • lib/local.dart - Hive database adapter for offline_sync_engine
  • lib/cloud.dart - Firebase cloud adapter for offline_sync_engine
  • lib/internet.dart - Connectivity monitoring service

πŸ› οΈ Setup Instructions

1. Firebase Setup

Create Firebase Project

  1. Go to Firebase Console
  2. Create a new project (or use existing)
  3. Enable Firebase Realtime Database

Add Firebase to Your App

For Android:

  1. Download google-services.json from Firebase Console
  2. Place it in android/app/google-services.json

For iOS:

  1. Download GoogleService-Info.plist from Firebase Console
  2. Place it in ios/Runner/GoogleService-Info.plist

For Web:

  1. Run flutterfire configure to generate Firebase options
  2. Follow the prompts to configure web support

Configure Database Rules

In Firebase Console β†’ Realtime Database β†’ Rules:

{
  "rules": {
    ".read": true,
    ".write": true,
    "notes": {
      ".indexOn": ["id"]
    },
    "operations": {
      ".indexOn": ["opId"]
    }
  }
}

⚠️ Note: These are permissive rules for development. Implement proper authentication and security rules for production.

2. Install Dependencies

flutter pub get

3. Run the App

# Android
flutter run -d android

# iOS
flutter run -d ios

# Web
flutter run -d chrome

πŸ“± How to Use

Adding Notes

  1. Online Mode: Type your note and press "Add"

    • Saves to local storage immediately
    • Syncs to Firebase automatically
    • Shows "Note added and synced to cloud" (green)
  2. Offline Mode: Type your note and press "Add"

    • Saves to local storage immediately
    • Note appears with "Local Only" status (orange indicator)
    • Will sync when internet connection is restored

Viewing Sync Status

Each note displays a status indicator:

  • 🟒 Synced - Present in both local storage and Firebase
  • 🟠 Local Only - Only in local storage, not yet synced to cloud
  • πŸ”΅ Cloud Only - Only in Firebase, not in local storage

Deleting Notes

  1. Press the delete icon (πŸ—‘οΈ) on any note
  2. Note is removed from local storage immediately
  3. If online, also removed from Firebase
  4. If offline, deletion will sync when connection is restored

Manual Actions

  • Sync Button (⟳) - Manually trigger sync with Firebase
  • Refresh Button (πŸ”„) - Reload notes from storage

Connectivity Indicator

The app bar shows real-time connection status:

  • 🟒 Online - Connected to internet, auto-sync enabled
  • πŸ”΄ Offline - No connection, using local storage only

πŸ’Ύ Data Storage

Local Storage (Hive)

Three Hive boxes are used:

  1. notes - Stores note data

    { "id": "uuid", "content": "Note text" }
  2. sync_operations - Tracks pending sync operations

    { "opId": "uuid", "type": "create/update/delete", ... }
  3. deleted_notes - Tombstone records for deleted items

    { "id": "uuid", "deletedAt": "timestamp", "cloudDeleted": false }

Cloud Storage (Firebase)

Firebase Realtime Database structure:

{
  "notes": {
    "note-uuid-1": {
      "id": "note-uuid-1",
      "content": "My first note"
    },
    "note-uuid-2": {
      "id": "note-uuid-2",
      "content": "Another note"
    }
  },
  "operations": {
    "op-uuid-1": {
      "opId": "op-uuid-1",
      "type": "create",
      // ... other sync metadata
    }
  }
}

πŸ”„ Sync Mechanism

How It Works

  1. Write Operations: When you add/update/delete a note:

    • Saved to local Hive storage immediately (works offline)
    • Operation queued in sync_operations box
    • If online, attempt to write to Firebase
    • If offline, operation stays queued
  2. Automatic Sync: When internet connection is detected:

    • ConnectivityService triggers automatic sync
    • Queued operations pushed to Firebase
    • Cloud data reconciled with local data
    • Sync operations cleaned up after success
  3. Conflict Resolution: Uses CRDT-based offline_sync_engine

    • Operations are commutative (order-independent)
    • Last-write-wins with timestamp-based resolution
    • Deterministic merging across devices

Sync Triggers

  • βœ… Internet connection restored (automatic)
  • βœ… Manual sync button pressed
  • βœ… App startup (if online)
  • βœ… After each create/update/delete operation (if online)

πŸ§ͺ Testing

Test Offline Mode

  1. Disable Internet:

    • Android Emulator: Open Settings β†’ Network & Internet β†’ Turn off WiFi
    • Device: Enable Airplane Mode
  2. Add Notes: Create several notes while offline

  3. Verify Local Storage: Notes should appear immediately with "Local Only" status

  4. Restart App: Close and reopen - notes should persist

  5. Enable Internet: Turn WiFi/data back on

  6. Auto-Sync: Watch notes sync automatically, status changes to "Synced"

  7. Check Firebase Console: Verify notes appear in Realtime Database under /notes/

Test Online Mode

  1. Add Note: Type and add a note
  2. Console Output: Should show:
    I/flutter: Note saved locally: abc-123
    I/flutter: Note saved to Firebase: abc-123
    I/flutter: Starting sync...
    I/flutter: Sync completed.
    
  3. Firebase Console: Note should appear immediately

Debug Console Messages

Enable debug logging to see sync operations:

// Already enabled in the app
print('Note saved locally: $id');
print('Note saved to Firebase: $id');
print('Starting sync...');
print('Sync completed.');

πŸ› Troubleshooting

Notes Not Syncing to Firebase

  1. Check Firebase Configuration:

    • Verify google-services.json (Android) or GoogleService-Info.plist (iOS) is present
    • Check Firebase Console for correct project ID
  2. Check Database Rules:

    • Ensure rules allow write access
    • Look for permission errors in console
  3. Check Internet Connection:

    • Verify connectivity indicator shows "Online"
    • Test with flutter run -v for detailed logs

Notes Not Showing When Offline

  1. Check Hive Initialization:

    • Ensure Hive.initFlutter() runs before data operations
    • Check app storage permissions
  2. Clear Cache (if needed):

    flutter clean
    flutter pub get

Firebase Timeout Errors

If you see timeout errors when offline, ensure:

  • loadNotesWithStatus(isOnline: _isConnected) is passing correct connectivity status
  • Firebase calls are wrapped in isOnline checks

🎯 Best Practices Implemented

βœ… Offline-First Design - App fully functional without internet
βœ… Optimistic UI Updates - Immediate user feedback
βœ… Error Handling - Graceful degradation on network errors
βœ… Status Indicators - Clear visual feedback of sync state
βœ… Data Persistence - Local storage ensures no data loss
βœ… Automatic Sync - Seamless cloud synchronization
βœ… CRDT Operations - Conflict-free distributed data structures

πŸ“ Future Enhancements

  • User authentication with Firebase Auth
  • Multi-device sync testing
  • Conflict resolution UI for manual intervention
  • Batch operations for better performance
  • Offline indicator with pending operations count
  • Export/import functionality
  • Search and filter capabilities
  • Note categories/tags
  • Rich text editor support

πŸ“„ License

This project is open source and available for educational purposes.

🀝 Contributing

Contributions are welcome! Feel free to:

  • Report bugs
  • Suggest new features
  • Submit pull requests
  • Improve documentation

πŸ“š Resources


Built with ❀️ using Flutter

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages