offline_first_fhir_client 0.0.6 copy "offline_first_fhir_client: ^0.0.6" to clipboard
offline_first_fhir_client: ^0.0.6 copied to clipboard

The offline_first_fhir_client library provides a comprehensive solution for managing and syncing FHIR resources in Flutter applications with offline-first capabilities. It is designed for developers b [...]

example/lib/main.dart

import 'package:example/edit_patient_data.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:offline_first_fhir_client/offline_first_fhir_client.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  // Initialize Hive
  await HiveService.initHive();


  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      title: 'Patient Data Manager',
      home: PatientInputScreen(),
    );
  }
}

class PatientInputScreen extends StatefulWidget {
  const PatientInputScreen({super.key});

  @override
  PatientInputScreenState createState() => PatientInputScreenState();
}

class PatientInputScreenState extends State<PatientInputScreen> {
  final _formKey = GlobalKey<FormState>();
  final _nameController = TextEditingController();
  final _genderController = TextEditingController();
  final _birthDateController = TextEditingController();

  // Instantiate services
  final hiveService = HiveService();
  final apiService = ApiService(baseUrl: "http://20.8.73.160:8080/fhir", authToken: "your-auth-token");

  final List<Map<String, dynamic>> _patients = [];

  bool isLoading = false;

  @override
  void dispose() {
    // Dispose of controllers to free resources
    _nameController.dispose();
    _genderController.dispose();
    _birthDateController.dispose();
    super.dispose();
  }

  @override
  void initState() {
    // Initialize state and fetch local patients
    _getPatients();
    super.initState();
  }

  /// Fetches all patient data from the local Hive database and updates the state.
  void _getPatients() async {
    _patients.clear();
    List<Map<String, dynamic>>? patientsData = await hiveService.getAllData("Patient");
    setState(() {
      _patients.addAll(patientsData);
    });
    }

  /// Add a new patient or update an existing one
  Future<void> _addPatient() async {
    if (_formKey.currentState!.validate()) {
      var name = _nameController.text.trim().split(" ");
      var firstName = name[0];
      var remainArr = name.sublist(1);
      var lastName = remainArr.join(" ");

      List<Map<String, dynamic>> searchResult = await hiveService.searchResourceByGivenKeys(
        "Patient",
        [
          {r'$.body.name[0].family': lastName},
          {r'$.body.name[0].given': [firstName]},
          {r'$.body.birthDate': {'type': 'equals', 'value': _birthDateController.text}},
        ],
      );

      final patient = {
        "id": DateTime.now().millisecondsSinceEpoch.toString(),
        "localVersionId": "1",
        "isSynced" : false,
        "body": {
          "resourceType": "Patient",
          "id": DateTime.now().millisecondsSinceEpoch.toString(),
          "name": [
            {"family": lastName, "given": [firstName]},
          ],
          "meta": {
            "versionId": "1",
            "lastUpdated": DateFormat("yyyy-MM-ddTHH:mm:ss.SSSXXX").format(DateTime.now().toUtc()),
            "source": DateTime.now().millisecondsSinceEpoch,
          },
          "birthDate": _birthDateController.text,
        },
      };

      if (searchResult.isNotEmpty) {
        _showDuplicateDialog(patient, searchResult[0]);
      } else {
        setState(() {
          _patients.add(patient);
        });
        await _savePatientToLocal(patient);
        _clearFormInputs();
      }
    }
  }

  void _showDuplicateDialog(Map<String, dynamic> newPatient, Map<String, dynamic> existingPatient) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text('Duplicate Patient'),
          content: const Text('A similar patient exists. Override or create a new entry?'),
          actions: [
            TextButton(
              onPressed: () {
                Navigator.of(context).pop();
                setState(() {
                  _patients.add(newPatient);
                });
                _savePatientToLocal(newPatient);
                _clearFormInputs();
                ScaffoldMessenger.of(context).showSnackBar(
                  const SnackBar(content: Text('New patient added locally!')),
                );
              },
              child: const Text('Create New'),
            ),
            TextButton(
              onPressed: () {
                Navigator.of(context).pop();
                existingPatient['body']['name'][0]['family'] = newPatient['body']['name'][0]['family'];
                existingPatient['body']['name'][0]['given'][0] = newPatient['body']['name'][0]['given'][0];
                existingPatient['body']['birthDate'] = newPatient['body']['birthDate'];
                _savePatientToLocal(existingPatient);
                _clearFormInputs();
                ScaffoldMessenger.of(context).showSnackBar(
                  const SnackBar(content: Text('Existing patient updated locally!')),
                );
              },
              child: const Text('Override'),
            ),
          ],
        );
      },
    );
  }

  Future<void> _savePatientToLocal(Map<String, dynamic> patient) async {
    final identifier = patient['id'];
    if (identifier != null) {
      await hiveService.saveData("Patient", identifier, patient);
    } else {
      throw Exception('Patient data must have a valid identifier.');
    }
  }

  void _clearFormInputs() {
    _nameController.clear();
    _birthDateController.clear();
  }

  /// Sync all patients to the server
  Future<void> _syncPatientsToServer() async {
    setState(() {
      isLoading = true;
    });

    try {
      List<Map<String, dynamic>>? localPatients = await hiveService.getAllData("Patient");
      String? nextUrl = "/Patient";

      List<dynamic> serverEntries = await apiService.getAllResourceDataWithPagination(nextUrl);

      if (serverEntries.isNotEmpty) {
        await _syncPatients(localPatients, serverEntries);
      } else {
        if (localPatients.isNotEmpty) {
          await _postAllPatients(localPatients);
        }
      }
      _getPatients();
    } catch (e) {
      if (kDebugMode) {
        print("Sync error: $e");
      }
    } finally {
      setState(() {
        isLoading = false;
      });
    }
  }

  /// Synchronizes local patients with server patients, resolving conflicts as needed.
  Future<void> _syncPatients(List<Map<String, dynamic>>? localPatients,
      List<dynamic> serverEntries) async {

    List<Map<String, dynamic>> remainingPatients =
    List.from(localPatients ?? []);

    for (var serverEntry in serverEntries) {
      var serverPatient = serverEntry['resource'];

      var matchedPatient = remainingPatients.firstWhere(
            (localPatient) => _isPatientMatch(localPatient, serverPatient),
        orElse: () => {},
      );

      if (matchedPatient.isNotEmpty) {
        remainingPatients.remove(matchedPatient);

        if (_isServerPatientNewer(serverPatient, matchedPatient)) {
          await _updateLocalPatient(serverPatient, matchedPatient['id']);
        } else {
          await _updateServerPatient(matchedPatient);
        }
      } else {
        await _updateLocalPatient(serverPatient, DateTime.now().millisecondsSinceEpoch.toString());
      }
    }

    if (remainingPatients.isNotEmpty) {
      await _postAllPatients(remainingPatients);
    }
  }

// Helper: Check if two patients match based on name, gender, birthdate, or identifier
  bool _isPatientMatch(Map<String, dynamic> local, Map<String, dynamic> server) {
    try {
      final localBody = local['body'];
      final serverBody = server;
      return serverBody['id'] == localBody['id'];
    } catch (e) {
      return false;
    }
  }

// Helper: Compare version IDs between server and local patient data
  bool _isServerPatientNewer(Map<String, dynamic> server, Map<String, dynamic> local) {
    final serverVersionId = int.parse(server['meta']['versionId'].toString());
    final localVersionId = int.parse(local['localVersionId'].toString());
    return serverVersionId >= localVersionId;
  }

// Helper: Update local patient data after successful server sync
  Future<void> _updateLocalPatient(Map<String, dynamic> serverPatient, String id) async {
    // Update the localVersionId with the server's meta.versionId
    var patient = {
      'id' : id,
      'localVersionId' : serverPatient['meta']['versionId'].toString(),
      'isSynced' : true,
      'body' : serverPatient
    };

    await hiveService.saveData(
      "Patient",
      patient['id'].toString(),
      patient,
    );
  }

// Helper: Update server with the local patient data
  Future<void> _updateServerPatient(Map<String, dynamic> localPatient) async {
    dynamic response = await apiService.putData(
      "/Patient/${localPatient['body']['id']}",
      localPatient['body'],
    );
    if (response != null) {
      final updatedPatient = {
        "id" : localPatient['id'],
        "localVersionId": response['meta']['versionId'].toString(),
        "isSynced" : true,
        "body": response,
      };
      await hiveService.saveData(
        "Patient",
        updatedPatient['id'],
        updatedPatient,
      );
    }
  }

// Helper: Post all unsynced patients to the server
  Future<void> _postAllPatients(List<Map<String, dynamic>> patients) async {
    for (var patient in patients) {
      if (!patient['isSynced']) {
        if (kDebugMode) {
          print("Posting patient to server...");
        }
        dynamic response = await apiService.postData("/Patient", patient['body']);
        if (response != null) {
          final updatedPatient = {
            'id' : patient['id'],
            "localVersionId": response['meta']['versionId'].toString(),
            "isSynced" : true,
            "body": response,
          };
          await hiveService.saveData(
            "Patient",
            updatedPatient['id'],
            updatedPatient,
          );
        }
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Patient Data Input'),
      ),
      body: Stack(
        children: [
          Padding(
            padding: const EdgeInsets.all(16.0),
            child: Column(
              children: [
                Form(
                  key: _formKey,
                  child: Column(
                    children: [
                      TextFormField(
                        controller: _nameController,
                        decoration: const InputDecoration(labelText: 'Name'),
                        validator: (value) {
                          if (value == null || value.isEmpty) {
                            return 'Please enter a name';
                          }
                          final namePattern = RegExp(r'^[A-Za-z]+( [A-Za-z]+)+$');
                          if (!namePattern.hasMatch(value.trim())) {
                            return 'Please enter at least first name and last name';
                          }
                          return null;
                        },
                      ),
                      TextFormField(
                        controller: _birthDateController,
                        decoration: const InputDecoration(labelText: 'Birth Date (YYYY-MM-DD)'),
                        validator: (value) {
                          if (value == null || value.isEmpty) {
                            return 'Please enter a birth date';
                          }
                          return null;
                        },
                      ),
                      const SizedBox(height: 20),
                      ElevatedButton(
                        onPressed: _addPatient,
                        child: const Text('Add Patient to Local'),
                      ),
                    ],
                  ),
                ),
                const SizedBox(height: 20),
                const Text('Patients From Local Database'),
                Expanded(
                  child: ListView.builder(
                    itemCount: _patients.length,
                    itemBuilder: (context, index) {
                      final patient = _patients[index];
                      return ListTile(
                        title: Text("${patient['body']['name'][0]['given'][0].toString()} ${patient['body']['name'][0]['family'].toString()}"),
                        subtitle: Text('${patient['body']['birthDate']}'),
                        trailing: Container(
                          width: 100,
                          alignment: Alignment.centerRight,
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.end,
                            children: [
                              GestureDetector(
                                  onTap: () {
                                    Navigator.of(context).push(CupertinoPageRoute(builder: (context) => EditPatientData(patient))).then((onValue) => _getPatients());
                                  },
                                  child: const Icon(Icons.edit, size: 18,)
                              ),
                              const SizedBox(width: 16,),
                              !patient['isSynced'] ? GestureDetector(
                                  onTap: () {
                                    showDialog(
                                      context: context,
                                      builder: (BuildContext context) {
                                        return AlertDialog(
                                          title: const Text('Alert'),
                                          content: const Text('This data is not synced to server, so it will be deleted permanently from local database, are you sure you want to delete?'),
                                          actions: [
                                            TextButton(
                                              onPressed: () async {
                                                Navigator.of(context).pop(); // Close the dialog
                                                await hiveService.deleteDataByKey("Patient", patient['id'].toString());
                                                setState(() {
                                                  _patients.removeAt(index);
                                                });
                                              },
                                              child: const Text('Delete', style: TextStyle(color: Colors.red),),
                                            ),
                                            TextButton(
                                              onPressed: () {
                                                Navigator.of(context).pop(); // Close the dialog
                                              },
                                              child: const Text('No'),
                                            ),
                                          ],
                                        );
                                      },
                                    );
                                  },
                                  child: const Icon(Icons.delete, size: 18, color: Colors.red,)
                              ) : Container(),
                            ],
                          ),
                        ),
                      );
                    },
                  ),
                ),
                const Text('New data will reflect on server within 5 mins'),
                ElevatedButton(
                  onPressed: isLoading ? null : _syncPatientsToServer,
                  child: Text( isLoading ? 'Syncing' : 'Sync All to Server'),
                ),
              ],
            ),
          ),
          isLoading ? Container(
            color: Colors.white54,
            child: const Center(
              child: CircularProgressIndicator(),
            ),
          ) : Container()
        ],
      ),
    );
  }
}
2
likes
0
points
145
downloads

Publisher

verified publishertdh.org

Weekly Downloads

The offline_first_fhir_client library provides a comprehensive solution for managing and syncing FHIR resources in Flutter applications with offline-first capabilities. It is designed for developers building healthcare applications where reliable data access is critical, even in offline scenarios.

Homepage
Repository (GitHub)
View/report issues

License

unknown (license)

Dependencies

flutter, flutter_secure_storage, hive_flutter, hive_generator, http, intl, json_path, mockito, path_provider, path_provider_platform_interface, workmanager

More

Packages that depend on offline_first_fhir_client