offline_first_fhir_client 0.0.30
offline_first_fhir_client: ^0.0.30 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 FhirClient
await FhirClient().initialize("https://fhir-server-persisted.wonderfulcliff-68cdbf49.westeurope.azurecontainerapps.io/hapi-fhir-jpaserver/fhir", "");
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 fhirClient = FhirClient();
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 fhirClient.getAllResources("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 fhirClient.searchResourceByGivenKeys(
"Patient",
[
{r'$.body.name[0].family': lastName},
{r'$.body.name[0].given': [firstName]},
{r'$.body.birthDate': {'type': 'equals', 'value': _birthDateController.text}},
],
);
var uniqueId = DateTime.now().millisecondsSinceEpoch.toString();
final patient = {
"id": uniqueId,
"localVersionId": "1",
"isSynced" : false,
"body": {
"resourceType": "Patient",
"id": uniqueId,
"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,
},
};
var uniqueOb1 = DateTime.now().millisecondsSinceEpoch.toString();
var uniqueOb2 = "1" + DateTime.now().millisecondsSinceEpoch.toString();
var uniqueOb3 = "2" + DateTime.now().millisecondsSinceEpoch.toString();
final observation = [
{
"id": uniqueOb1,
"localVersionId": "1",
"isSynced" : false,
"body" : {
"resourceType": "Observation",
"id" : uniqueOb1,
"status": "final",
"category": [
{
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/observation-category",
"code": "vital-signs",
"display": "Vital Signs"
}
]
}
],
"code": {
"coding": [
{
"system": "http://loinc.org",
"code": "91942-7",
"display": "Gestational age"
}
]
},
"subject": {
"reference": "Patient/$uniqueId"
},
"effectiveDateTime": "2025-01-10T08:00:00+00:00",
"valueQuantity": {
"value": 38,
"unit": "weeks",
"system": "http://unitsofmeasure.org",
"code": "wk"
},
"extension": [
{
"url": "http://example.org/fhir/StructureDefinition/determination-method",
"valueString": "Date of last menstrual period"
},
{
"url": "http://example.org/fhir/StructureDefinition/determination-date",
"valueDateTime": "2025-01-01"
}
]
}
},
{
"id": uniqueOb2,
"localVersionId": "1",
"isSynced" : false,
"body" : {
"resourceType": "Observation",
"id" : uniqueOb2,
"status": "final",
"category": [
{
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/observation-category",
"code": "vital-signs",
"display": "Vital Signs"
}
]
}
],
"code": {
"coding": [
{
"system": "http://loinc.org",
"code": "10220-3",
"display": "Start of labor"
}
]
},
"subject": {
"reference": "Patient/$uniqueId"
},
"effectiveDateTime": "2025-01-10T08:00:00+00:00",
"valueString": "Spontaneous"
}
},
{
"id": uniqueOb3,
"localVersionId": "1",
"isSynced": false,
"body": {
"resourceType": "Observation",
"id": uniqueOb3,
"status": "final",
"category": [
{
"coding": [
{
"system":
"http://terminology.hl7.org/CodeSystem/observation-category",
"code": "survey",
"display": "Survey"
}
]
}
],
"code": {
"coding": [
{
"system": "http://loinc.org",
"code": "11996-6",
"display": "Gravidity"
}
]
},
"subject": {"reference": "Patient/$uniqueId"},
"effectiveDateTime": DateFormat("yyyy-MM-ddTHH:mm:ss.SSSXXX")
.format(DateTime.now().toUtc()),
"valueQuantity": {"value": "2", "unit": "pregnancies"}
}
}
];
var uniqueCon1 = DateTime.now().millisecondsSinceEpoch.toString();
var uniqueCon2 = DateTime.now().millisecondsSinceEpoch.toString();
final condition = [
{
"id": uniqueCon1,
"localVersionId": "1",
"isSynced" : false,
"body" : {
"resourceType": "Condition",
"id" : uniqueCon1,
"clinicalStatus": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/condition-clinical",
"code": "active"
}
]
},
"verificationStatus": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/condition-ver-status",
"code": "confirmed"
}
]
},
"code": {
"coding": [
{
"system": "http://snomed.info/sct",
"code": "38341003",
"display": "Chronic hypertension"
}
]
},
"subject": {
"reference": "Patient/$uniqueId"
}
},
},
{
"id": uniqueCon2,
"localVersionId": "1",
"isSynced" : false,
"body" : {
"resourceType": "Condition",
"id" : uniqueCon2,
"clinicalStatus": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/condition-clinical",
"code": "active"
}
]
},
"verificationStatus": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/condition-ver-status",
"code": "confirmed"
}
]
},
"code": {
"coding": [
{
"system": "http://snomed.info/sct",
"code": "6342002",
"display": "Preeclampsia"
}
]
},
"subject": {
"reference": "Patient/$uniqueId"
}
}
}
];
var uniqueFlag1 = DateTime.now().millisecondsSinceEpoch.toString();
final flag = [
{
"id": uniqueFlag1,
"localVersionId": "1",
"isSynced" : false,
"body" : {
"resourceType": "Flag",
"id" : uniqueFlag1,
"status": "active",
"category": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/flag-category",
"code": "safety",
"display": "Safety"
}
]
},
"code": {
"coding": [
{
"system": "http://snomed.info/sct",
"code": "431855005",
"display": "HIV infection"
}
]
},
"subject": {
"reference": "Patient/$uniqueId"
},
"note": [
{
"text": "Patient diagnosed with HIV."
}
]
}
}
];
if (searchResult.isNotEmpty) {
_showDuplicateDialog(patient, observation, condition, flag, searchResult[0]);
} else {
setState(() {
_patients.add(patient);
});
await _savePatientToLocal(patient);
await _saveObservationToLocal(observation);
await _saveConditionToLocal(condition);
await _saveFlagToLocal(flag);
_clearFormInputs();
}
}
}
void _showDuplicateDialog(Map<String, dynamic> newPatient, List<Map<String, Object>> observation, List<Map<String, Object>> condition, List<Map<String, Object>> flag, 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);
_saveObservationToLocal(observation);
_saveConditionToLocal(condition);
_saveFlagToLocal(flag);
_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 fhirClient.saveResource("Patient", identifier, patient);
} else {
throw Exception('Patient data must have a valid identifier.');
}
}
Future<void> _saveObservationToLocal(List<Map<String, dynamic>> observation) async {
for (var obs in observation) {
final identifier = obs['id'];
if (identifier != null) {
await fhirClient.saveResource("Observation", identifier, obs);
} else {
throw Exception('Patient data must have a valid identifier.');
}
}
}
Future<void> _saveConditionToLocal(List<Map<String, dynamic>> condition) async {
for (var con in condition) {
final identifier = con['id'];
if (identifier != null) {
await fhirClient.saveResource("Condition", identifier, con);
} else {
throw Exception('Patient data must have a valid identifier.');
}
}
}
Future<void> _saveFlagToLocal(List<Map<String, dynamic>> flag) async {
for (var f in flag) {
final identifier = f['id'];
if (identifier != null) {
await fhirClient.saveResource("Flag", identifier, f);
} else {
throw Exception('Patient data must have a valid identifier.');
}
}
}
void _clearFormInputs() {
_nameController.clear();
_birthDateController.clear();
}
/// Sync all resources (Patients, Observations, Conditions, Flags) to the server
Future<void> _syncPatientsToServer() async {
setState(() {
isLoading = true;
});
try {
/*var endpoints = {
"Organization": "/Organization",
"Practitioner": "/Practitioner",
"PractitionerRole": "/PractitionerRole",
};*/
Map<String, String> endpoints = {};
var serverUrl = "/Patient/\$everything";
var resources = [
"Patient",
"Observation",
"Condition",
"Flag"
];
await fhirClient.syncResources(endpoints, serverUrl, resources);
_getPatients();
/*// Fetch local data for all resource types
List<Map<String, dynamic>>? localPatients = await fhirClient.getAllData("Patient");
List<Map<String, dynamic>>? localObservations = await fhirClient.getAllData("Observation");
List<Map<String, dynamic>>? localConditions = await fhirClient.getAllData("Condition");
List<Map<String, dynamic>>? localFlags = await fhirClient.getAllData("Flag");
// Fetch all server data for all resources
String? nextUrl = "/Patient/\$everything";
List<dynamic> serverEntries = await fhirClient.getAllResourceDataWithPagination(nextUrl);
// Sync Patients first to get updated IDs
final updatedPatientIds = await fhirClient.syncResources("Patient", localPatients, serverEntries, r'$[?(@.resource.resourceType == "Patient")].resource', apiService);
// Sync other resources, updating their references with the new patient IDs
await SyncHelper().syncResourcesWithUpdatedReferences("Observation", localObservations, serverEntries, r'$[?(@.resource.resourceType == "Observation")].resource', updatedPatientIds, apiService);
await SyncHelper().syncResourcesWithUpdatedReferences("Condition", localConditions, serverEntries, r'$[?(@.resource.resourceType == "Condition")].resource', updatedPatientIds, apiService);
await SyncHelper().syncResourcesWithUpdatedReferences("Flag", localFlags, serverEntries, r'$[?(@.resource.resourceType == "Flag")].resource', updatedPatientIds, apiService);
_getPatients();*/
} catch (e) {
if (kDebugMode) {
print("Sync error: $e");
}
} finally {
setState(() {
isLoading = false;
});
}
}
Map<String, dynamic> removeEmptyFields(Map<String, dynamic> data) {
// Ensure the map is strongly typed
data = Map<String, dynamic>.from(data);
data.removeWhere((key, value) {
if (value == null || value.isEmpty || (value is List && value.isEmpty)) {
return true; // Remove if null, empty string, or empty list
}
if (value is Map) {
// Recursively clean nested maps
data[key] = removeEmptyFields(Map<String, dynamic>.from(value));
return (data[key] as Map).isEmpty;
}
if (value is List) {
// Recursively clean each element in a list
data[key] = value
.where((element) =>
element is! Map ||
removeEmptyFields(Map<String, dynamic>.from(element)).isNotEmpty)
.toList();
return (data[key] as List).isEmpty;
}
return false;
});
return data;
}
@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 fhirClient.deleteResourceByKey("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()
],
),
);
}
}