"# offline_first_fhir_client"

Table of Contents

  1. Flutter Package Flow Overview
  2. Package Folder Structure
  3. Package Dependencies and Classes Descriptions
  4. Resource Synchronization Flow and Best Practices for Conflict Resolution
  5. Flutter Package Library Overview
  6. Setting Up A Flutter Package In Android Studio

---
title: Flutter Package Flow
config:
  background-color: #FFFAF0
---
flowchart TB
    style containerBG fill:#FFFAF0,stroke:#333,stroke-width:2px,rx:10,ry:10
    
    subgraph containerBG[ ]

    classDef appStyle fill:#F0E68C,stroke:#333,stroke-width:2px,font-size:16px,font-weight:bold
    classDef syncStyle fill:#98FB98,stroke:#333,stroke-width:2px,font-size:16px,font-weight:bold
    classDef dbStyle fill:#87CEFA,stroke:#333,stroke-width:2px,font-size:16px,font-weight:bold
    classDef internetStyle fill:#FFA07A,stroke:#333,stroke-width:2px,font-size:16px,font-weight:bold
    classDef authStyle fill:#DDA0DD,stroke:#333,stroke-width:2px,font-size:16px,font-weight:bold
    classDef conflictStyle fill:#F0E68C,stroke:#333,stroke-width:2px,font-size:16px,font-weight:bold
    classDef serverStyle fill:#40E0D0,stroke:#333,stroke-width:2px,font-size:16px,font-weight:bold
    
    APP["**App Layer**<br>- Manages UI and User Inputs<br>- Flutter Packages for:<br>  1. User Interface<br>  2. Data Collection<br>  3. User Authentication"]:::appStyle
    
    SYNC_LOGIC["**Sync Logic**<br>- Manual Sync<br>- Scheduled Sync (3x/week)<br>- Automated Sync Mechanisms"]:::syncStyle
    
    DATABASE_OPS["**Database Operations**<br>- CRUD Operations<br>- Resource Management<br>- Data Manipulation"]:::dbStyle
    
    FIRST_TIME_INTERNET["**First-Time Internet Setup**<br>- Fetch Data from HAPI FHIR<br>- Initial Data Synchronization<br>- Secure Data Retrieval"]:::internetStyle
    
    HIVE_DB["**Hive NoSQL Database**<br>- JSON Data Storage<br>- HIPAA Compliant<br>- Resource Management<br>- Encrypted Storage"]:::dbStyle
    
    AUTH_BLOCK["**Authentication & API Block**<br>- Secure Authentication<br>- HAPI FHIR API Calls<br>- Resource CRUD Operations"]:::authStyle
    
    CONFLICT_RESOLUTION["**Conflict Resolution Strategy**<br>- Internet Sync Issues Handling<br>- Local Data Preservation<br>- Status Management"]:::conflictStyle
    
    SERVER_BLOCK["**HAPI FHIR Server**<br>- Resource Storage<br>- Data Synchronization<br>- Server-Side Management"]:::serverStyle
    
    APP <-->|"Custom Actions/Data"| SYNC_LOGIC
    APP <-->|"Custom Actions/Data"| DATABASE_OPS
    APP <-->|"Custom Actions/Data"| FIRST_TIME_INTERNET
    
    SYNC_LOGIC <--> HIVE_DB
    DATABASE_OPS <--> HIVE_DB
    FIRST_TIME_INTERNET <--> HIVE_DB
    
    HIVE_DB <--> AUTH_BLOCK
    
    AUTH_BLOCK <--> CONFLICT_RESOLUTION
    AUTH_BLOCK <--> SERVER_BLOCK
    
    CONFLICT_RESOLUTION <--> SERVER_BLOCK
    end

Flutter Package Flow Overview

The Flutter Package Flow illustrates the architecture of the application, focusing on key components involved in data management and synchronization. Key elements include:

  • App Layer: Manages the user interface and user inputs through Flutter packages for UI, data collection, and authentication.
  • Sync Logic: Handles manual and scheduled synchronization (three times a week), including automated mechanisms.
  • Database Operations: Performs CRUD operations and resource management within the database.
  • First-Time Internet Setup: Fetches initial data from the HAPI FHIR server and ensures secure data retrieval.
  • Hive NoSQL Database: Stores data in JSON format, ensuring HIPAA compliance with encrypted storage for resource management.
  • Authentication & API Block: Manages secure authentication and HAPI FHIR API calls for CRUD operations.
  • Conflict Resolution Strategy: Addresses sync issues, preserves local data, and manages status during conflicts.
  • HAPI FHIR Server: Responsible for resource storage, data synchronization, and server-side management.

This flow ensures efficient data handling and synchronization within the application.

Package Folder Structure

(package_name)/                           # Package name will come here
│
├── lib/                                  # Contains the main source code for the package.
│   ├── src/                              # Private classes and implementations.
│   │   ├── api/                          # API-related functionalities.
│   │   |── syncing/                   # Logic for data synchronization.
│   │   ├── database/                     # Database-related functionalities.
│   │   │── conflict_resolution/        # Logic for handling conflicts.
│   │   │── encryption/                 # Encryption-related logic.
│   │   └── (package_name).dart           # Core functionalities of the package.
│   ├── (package_name).dart               # public class with public functions exposed to flutter flow.
├── example/                              # Contains an example Flutter application demonstrating how to use the package.
│   ├── lib/                              # Example application code.
│   │   └── main.dart                     # Main entry point of the example app.
│   └── pubspec.yaml                      # Dependencies for the example app.
│
├── test/                                 # Contains unit tests for the package.
│   ├── api/                              # Tests for API functionalities.
│   ├── database/                         # Tests for database functionalities.               
│   └── (package_name).dart               # Tests for core functionalities of the package.
│
├── .gitignore                            # Specifies files and directories to be ignored by Git.
├── analysis_options.yaml                 # Configuration for Dart analysis.
├── CHANGELOG.md                          # Records changes and updates to the package.
├── LICENSE                               # License information for the package.
├── pubspec.lock                          # Locked dependencies for the package.
├── pubspec.yaml                          # Package configuration and dependencies.
└── README.md                             # Documentation for the package.
---
title: Package Dependencies Classes
---
classDiagram
    direction LR
    class EncryptionHelper {
        +storeEncryptionKey()
        +retrieveEncryptionKey()
        +generateSecureKey()        
    }
    class DatabaseController {
        +initializeHiveDatabase()
        +createData()
        +readData()
        +updateData()
        +deleteData()
        +resolveConflicts()
    }
    class SyncScheduler {
        -syncInterval: Duration
        +scheduleSyncOperation()
        +runPeriodicSync()
        +triggerManualSync()
    }
    class InternetChecker {
        +checkConnectivity()
        +monitorInternetStatus()
        +isInternetAvailable(): Boolean
    }
    class ApiService {
        +authorization()
        +postRequest()
        +putRequest()
        +deleteRequest()
        +getRequest()
        +updateRequest()
        +resolveApiConflicts()
    }
    EncryptionHelper <--> DatabaseController: secure data storage
    DatabaseController <--> SyncScheduler: data sync management
    SyncScheduler <--> InternetChecker: connectivity verification
    InternetChecker <--> ApiService: network status

Package Dependencies Classes Descriptions

DatabaseController

This class will handle the integration and operations for the Hive database. It will include CRUD functions (Create, Read, Update, Delete) and conflict resolution logic for database operations.

Key Functionalities:

  • Hive Initialization: Functions to initialize the Hive database.
  • Data Management: Functions to create, update, delete, and fetch data.

ApiService

This class will handle all API calls and manage authorization for syncing purposes.

Key Functionalities:

  • API Methods: Support for POST, PUT, DELETE, GET, and UPDATE requests.
  • Conflict Resolution: Logic during API operations to handle conflicts.

SyncScheduler

This class will manage the scheduling of data syncing tasks.

Key Functionalities:

  • Scheduling Logic: Schedule sync operations every 2 days using appropriate scheduling techniques.

EncryptionHelper

This class will handle encryption-related logic, particularly for securely storing and retrieving encryption keys.

Key Functionalities:

  • Key Management: Manage the encryption key using the flutter_secure_storage library.

InternetChecker

This class will check the internet connection status.

Key Functionalities:

  • Connectivity Monitoring: Logic to monitor and verify internet connectivity using the connectivity_plus library.
flowchart LR
    A[Initial Resource Sync] --> B[Watermark Initialization]
    B --> C{Sync Strategy}

    %% Cache Preservation on the left
    subgraph Cache_Preservation[Cache Preservation]
        direction LR
        G[Local Changes Cache]
        H{Conflict Detection}
        I[Prepare Cached Changes]
        J[Merge Strategy]
        G --> H
        H --> |Local Changes Exist| I
        I --> J
    end

    %% Watermark Management on the right
    subgraph Watermark_Management[Watermark Management]
        direction LR
        D[Store Last Sync Timestamp]
        E[Fetch Updates with Watermark]
        F[Update Watermark]
        D --> E
        E --> F
    end

    %% Server Resource Retrieval and Conflict Detection
    C --> |Fetch Updates| K[Server Resource Retrieval]
    K --> L{Conflict Detection}

    L --> |Version Conflict| M[Version ID Mismatch]
    M --> M_note
    M_note["Occurs when **meta.versionId** of client differs from server.\nIndicates server resource has been updated."]
    
    L --> |Timestamp Conflict| N[Timestamp Comparison]
    N --> N_note
    N_note["Compares **meta.lastUpdated** timestamps to determine which resource is newer."]
    
    L --> |Deletion Conflict| O[Resource Deletion Check]
    L --> |Deduplication Conflict| P[Duplicate Record Identification]
    
    P --> P_note
    P_note[/"Identifies and resolves:
    - Matching patient records 
    - Redundant resource entries
    - Prevents data duplication
    - Ensures single source of truth"/]
    
    L --> |Batching/Transaction Conflict| Q[Batch Update Validation]
    
    Q --> Q_note
    Q_note[/"Handles complex update scenarios:
    - Atomic transaction integrity
    - Validate bundle updates
    - Ensure all-or-nothing updates
    - Prevent partial data modifications"/]

    %% Conflict Resolution
    subgraph Conflict_Resolution[Conflict Resolution]
        direction LR
        R{Resolution Strategy}
        S[Predefined Merge Algorithm]
        T[User Intervention]
        U[Merge Local & Server Changes]
       
        M --> R
        N --> R
        O --> R
        P --> R
        Q --> R
       
        R --> |Automatic Merge| S
        R --> |Manual Resolution| T
       
        S --> U
        T --> U
    end

    %% Update Process
    U --> V[Update Local Cache]
    V --> W[Server Update Attempt]

    W --> X{Update Successful?}
    X --> |Yes| Y[Commit Changes]
    X --> |No| Z[Rollback/Retry]

    Z --> C
    Y --> AA[Update Watermark]
    AA --> AB[Sync Complete]

    %% Styling for clarity
    style A fill:#f9f,stroke:#333,stroke-width:2px
    style C fill:#bbf,stroke:#333,stroke-width:2px
    style L fill:#bfb,stroke:#333,stroke-width:2px
    style R fill:#ff9,stroke:#333,stroke-width:2px

Resource Synchronization Flow and Best Practices for Conflict Resolution

Section 1: Explanation of the Resource Synchronization Flow Diagram

The resource synchronization process ensures consistency between local and server data while addressing conflicts and maintaining system integrity. The flow diagram comprises several stages, each focusing on specific aspects of synchronization. Below is a breakdown of the process:

Key Stages in the Flow Diagram

Watermark Management

  • Tracks the last synchronization point using timestamps to fetch only the required updates.
  • Includes components like storing the last sync timestamp, fetching updates, and updating the watermark.

Conflict Detection

Compares local and server data for discrepancies:

  • Version Conflict (meta.versionId): Occurs when the client and server have different version IDs for a resource.
  • Timestamp Conflict (meta.lastUpdated): Detects differences in the last update timestamps.
  • Deletion Conflict: Ensures no deleted resources are reintroduced.
  • Deduplication Conflict: Identifies duplicate records for unique entities like patients.

Conflict Resolution

Implements resolution strategies to merge changes:

  • Automatic merging using predefined algorithms.
  • Manual intervention for critical or complex conflicts.

Cache Preservation

Manages local changes to ensure they are not overwritten during synchronization:

  • Identifies conflicts with server updates.
  • Merges cached changes with server data.

Final Updates

  • Updates local caches and server data:
    • Commits successful updates to the server.
    • Rolls back and retries failed attempts.

While the flow diagram addresses key synchronization conflicts, additional challenges and best practices are highlighted below:

Challenges Not Addressed in the Flow Diagram

Battery Life Optimization

  • Challenge: Prolonged app usage can drain device batteries, disrupting access to critical data.
  • Best Practices:
    • Optimize app for low power consumption.
    • Provide portable power solutions.

Device Theft or Loss

  • Challenge: Lost devices may result in data breaches and loss of sensitive information.
  • Best Practices:
    • Encrypt local data and implement remote wipe features.
    • Use cloud backups to ensure data retrievability.

Connectivity Issues

  • Challenge: Inconsistent internet connectivity can hinder real-time synchronization.
  • Best Practices:
    • Design the app for offline-first operation with queued syncs.
    • Provide mobile hotspot devices.

Central System Overload

  • Challenge: High server load during simultaneous sync attempts may slow performance.
  • Best Practices:
    • Use rate-limiting and distributed servers to handle peak loads.

Limited Local Storage

  • Challenge: Devices with limited storage struggle to manage large datasets.
  • Best Practices:
    • Employ data compression and auto-cleanup for old data.
    • Enable external storage options.

Data Duplication

  • Challenge: Multiple registrations for the same entity can create duplicates.
  • Best Practices:
    • Use unique identifiers (e.g., National ID).
    • Integrate duplicate detection mechanisms.

Priority Resolution

  • Challenge: Conflicts over which update takes precedence can occur.
  • Best Practices:
    • Define priorities (e.g., recent updates).
    • Allow manual resolution for critical fields.

Record Ownership

  • Challenge: Disputes among users over data ownership can affect management.
  • Best Practices:
    • Assign primary ownership roles for records.
    • Enable supervisors to resolve disputes.

Data Transfer During Device Replacement

  • Challenge: Moving local data to a new device risks data loss.
  • Best Practices:
    • Use cloud backups and secure transfer tools.

Conclusion

The resource synchronization flow diagram provides a robust framework for managing conflicts, ensuring consistency, and resolving synchronization challenges. By incorporating additional best practices for challenges beyond synchronization, organizations can create a comprehensive and resilient system for managing patient data and other resources.

flowchart TD
    A[Flutter Package] --> B[Hive Flutter]
    A --> C[Flutter Secure Storage]
    A --> D[Path Provider]
    A --> E[HTTP]
    A --> F[Work Manager]
    A --> G[Connectivity Plus]

    %% Hive Flutter details
    B --> B1[Encrypted NoSQL DB: Stores data in JSON format]
    B1 --> B2[CRUD Operations: Perform basic database operations]
    B2 --> B3[32-Byte Encryption Key: Unique per user for data security]

    %% Flutter Secure Storage details
    C --> C1[Store Encryption Keys: Secure app environment]

    %% Path Provider details
    D --> D1[Access Device Storage: Saves Hive DB file securely]

    %% HTTP details
    E --> E1[API Calls: For syncing data with the server]

    %% Work Manager details
    F --> F1[Schedule Sync Every 2 Days: Automated task scheduling]

    %% Connectivity Plus details
    G --> G1[Check Internet Connection: Ensures connectivity for sync]

    %% Flutter Flow Integration
    H[Flutter Flow] --> I[Local DB & API Operations: Use Flutter package functions]
    H --> J[Syncing via Custom Actions: Handle data sync tasks]
    
    %% Libraries used in Flutter Flow
    I --> L[Use Libraries from Flutter Package: Integration in Flutter Flow]
    J --> L

    %% Styling for colors
    style A fill:#f9f,stroke:#333,stroke-width:2px
    style B fill:#bbf,stroke:#333,stroke-width:2px
    style C fill:#bbf,stroke:#333,stroke-width:2px
    style D fill:#bbf,stroke:#333,stroke-width:2px
    style E fill:#bbf,stroke:#333,stroke-width:2px
    style F fill:#bbf,stroke:#333,stroke-width:2px
    style G fill:#bbf,stroke:#333,stroke-width:2px
    style H fill:#ff9,stroke:#333,stroke-width:2px
    style I fill:#ff9,stroke:#333,stroke-width:2px
    style J fill:#ff9,stroke:#333,stroke-width:2px
    style L fill:#ff9,stroke:#333,stroke-width:2px
    style B1 fill:#eef,stroke:#333,stroke-width:2px
    style B2 fill:#eef,stroke:#333,stroke-width:2px
    style B3 fill:#eef,stroke:#333,stroke-width:2px
    style C1 fill:#eef,stroke:#333,stroke-width:2px
    style D1 fill:#eef,stroke:#333,stroke-width:2px
    style E1 fill:#eef,stroke:#333,stroke-width:2px
    style F1 fill:#eef,stroke:#333,stroke-

Flutter Package Library Overview

1. hive_flutter

  • Purpose: This library is used for encrypted NoSQL local database storage in Flutter. The data will be stored in JSON format, allowing universal use without the need to create model classes.
  • Key Features:
    • Common CRUD functions for database operations.
    • Smaller package size, making it adaptable for all types of resources.
    • 32-byte encryption key for securing the database, unique for each user.
    • Hive database file will be created in the app's data directory with a .hive extension, ensuring it is secure and not accessible by third-party tools.

2. flutter_secure_storage

  • Purpose: This library is used to store encryption keys securely in the app's secure storage environment.
  • Key Features:
    • Ensures that sensitive data, such as encryption keys, is stored in a secure, encrypted manner.

3. path_provider

  • Purpose: Required by Hive to access device storage.
  • Key Features:
    • Allows the app to locate appropriate storage directories on the device, necessary for storing the Hive database.

4. http

  • Purpose: This library will be used for making API calls.
  • Key Features:
    • Facilitates HTTP requests for syncing and interacting with server resources.

5. Workmanager

  • Purpose: This library is used for scheduling periodic sync tasks, specifically running tasks every 2 days.
  • Key Features:
    • Enables background task scheduling, such as syncing data at regular intervals.

6. connectivity_plus

  • Purpose: This library is used to check internet connection status for syncing or API-related operations.
  • Key Features:
    • Helps in managing internet connectivity checks, ensuring that sync operations occur only when a connection is available.

Flutter Flow Integration

1. Flutter Package that We Will Publish

  • Purpose: This package will be used for local database operations, API calls, and syncing tasks.
  • Integration:
    • Functions from the Flutter package will be exposed as custom actions within Flutter Flow, allowing seamless integration of database and sync functionalities in Flutter Flow projects.

2. Libraries Used in Flutter Package

  • All libraries used in the Flutter package (such as hive_flutter, flutter_secure_storage, path_provider, http, Workmanager, and connectivity_plus) will also be utilized in Flutter Flow.
  • Role: These libraries will support the functionalities of the Flutter package, ensuring that Flutter Flow can utilize the same resources for managing database operations, API calls, and background tasks.

Setting Up a Flutter Package in Android Studio

This guide will help you set up Flutter (SDK version 3.24.3, Dart SDK version 3.5.3) for development in Android Studio. Follow these steps to ensure everything is configured properly.

Prerequisites

Before starting, ensure you have the following installed:

  • Flutter SDK 3.24.3
  • Dart SDK 3.5.3
  • Android Studio Download here
  • Java Development Kit (JDK) (recommended version: JDK 17 or JDK 11)
  • Git

Steps

  1. Install Flutter SDK

    • Download Flutter SDK
    • Extract and Add to PATH
      • Extract the downloaded file to your preferred location (e.g., C:\flutter on Windows or ~/flutter on macOS/Linux).
      • Add the flutter/bin directory to your system's PATH:
        • Windows: Add C:\flutter\bin to the PATH in Environment Variables.
        • macOS/Linux: Add export PATH="$PATH:/path/to/flutter/bin" to your shell configuration file (e.g., .zshrc or .bashrc).
    • Verify Installation
      • Run the following command in your terminal to verify the installation:
        flutter doctor
        
      • Ensure there are no errors for Flutter, Dart, or Android Studio.
  2. Install Android Studio

    • Download and Install
      • Download Android Studio from the official site.
      • Install and open Android Studio.
    • Install Flutter and Dart Plugins
      • Open Android Studio.
      • Go to File > Settings > Plugins (or Preferences > Plugins on macOS).
      • Search for and install Flutter and Dart plugins.
      • Restart Android Studio.
    • Configure SDKs
      • Ensure Android Studio has the appropriate SDKs:
        • Open File > Settings > Appearance & Behavior > System Settings > Android SDK.
        • Select the latest Android API levels.
        • Download necessary build tools and platforms.
  3. Set Up a Flutter Project

    • Open an Existing Project
      • To open an existing Flutter project:
        • Go to File > Open.
        • Navigate to the directory of your Flutter project.
        • Select the folder and click OK.
    • Change Base URL
      • Open example/lib/main.dart.
      • Search for this line of code:
        final apiService = ApiService(baseUrl: "http://192.168.1.8:8080/fhir", authToken: "your-auth-token");
        
      • Change the baseUrl IP (192.168.1.8) to your localhost IP.

Steps to Configure and Run the Example App

  1. Open the Flutter Package in Android Studio

    • Launch Android Studio.
    • Select Open from the welcome screen or navigate to File > Open.
    • Locate the root folder of your Flutter package and open it.
    • Android Studio will automatically detect the Flutter project.
  2. Locate the Example App

    • In the Project Explorer, navigate to the example folder inside your Flutter package.
    • Verify that the example folder contains a Flutter app with a pubspec.yaml file.

Example Folder Structure

(my_flutter_package)/
├── example/  
│   ├── lib/  
│   ├── pubspec.yaml  
│   └── main.dart 
├── lib/  
├── pubspec.yaml  
└── README.md   
  1. Set Up the Example App Configuration
  • To run the example app, Android Studio needs to recognize the example app as a runnable configuration:
    • Go to Run > Edit Configurations.
    • Click the + button to create a new configuration.
    • Select Flutter as the configuration type.
    • Fill in the details:
      • Name: Enter a name for the configuration (e.g., Example App).
      • Project: Ensure the root project path points to your Flutter package.
      • Entry Point: Set the path to example/lib/main.dart.
        • Example Entry Point Path:
          /path_to_your_package/example/lib/main.dart
          
    • Click OK to save the configuration.
  1. Select a Target Device
  • Connect a physical Android device via USB, or start an Android Emulator.
  • In the device dropdown at the top-right corner of Android Studio, select your target device.
  1. Run the Example App
  • Ensure your newly created configuration (Example App) is selected in the configurations dropdown.
  • Click the Run button (green play icon) or press Shift + F10.
  • Android Studio will build and launch the example app on the selected device or emulator.