health_connector 3.3.0
health_connector: ^3.3.0 copied to clipboard
The most comprehensive Flutter health plugin for seamless iOS HealthKit and Android Health Connect integration.
health_connector #
Production-grade Flutter SDK for iOS HealthKit and Android Health Connect. Access 100+ health data types with compile-time type safety, Synchronize Data, and privacy-first architecture.
๐ Table of Contents #
-
โฌ๏ธ Migration Guide v2.x.x โ v3.0.0
๐ฎ See It In Action โ Interactive Toolbox Demo #
See what's possible. The Health Connector Toolbox showcases the full power of the SDK with live, interactive demonstrations running on both iOS and Android.
| ๐ Permissions | ๐ Read | โ๏ธ Write | ๐๏ธ Delete | ๐ Aggregate |
|---|---|---|---|---|
| [Permission Request] | [Read Data] | [Write Data] | [Delete Data] | [Aggregate Data] |
| [Permission Request] | [Read Data] | [Write Data] | [Delete Data] | [Aggregate Data] |
๐ Try It Yourself #
git clone https://github.com/fam-tung-lam/health_connector.git
cd health_connector/examples/health_connector_toolbox
flutter pub get && flutter run
Note: The toolbox app is used only for demonstration purposes and as an internal tool for manually testing SDK features. It is not intended for production reference.
๐ Quick Start #
๐ Requirements #
| Component | Requirements |
|---|---|
| Flutter | โข SDK: โฅ3.35.7 |
| Android | โข OS: API 26+ โข Languages: Kotlin 2.1.0, Java 17 |
| iOS | โข OS: โฅ15.0 โข Language: Swift 5.9 |
โจ Upgrading is Easy:
Flutter 3.35.7 has great backward compatibility up to Flutter 3.32.0, making the migration very straightforward and requiring no changes to your existing code. For projects already using Material 3 UI, great backward compatibility extends up to Flutter 3.27.0.
Swift 5.9 has great backward compatibility up to Swift 5.0, and Kotlin 2.1 up to Kotlin 2.0. Migration is very straightforward โ simply update version in your build configuration files. No changes to your existing native code are required.
๐ฆ Installation #
flutter pub add health_connector
Or add manually to pubspec.yaml:
dependencies:
health_connector: [ latest_version ]
๐ง Platform Setup #
๐ค Android Health Connect Setup
Step 1: Update AndroidManifest.xml
Update android/app/src/main/AndroidManifest.xml:
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<application>
<!-- Your existing configuration -->
<!-- Health Connect intent filter for showing permissions rationale -->
<activity-alias android:name="ViewPermissionUsageActivity" android:exported="true"
android:targetActivity=".MainActivity"
android:permission="android.permission.START_VIEW_PERMISSION_USAGE">
<intent-filter>
<action android:name="androidx.health.ACTION_SHOW_PERMISSIONS_RATIONALE" />
</intent-filter>
</activity-alias>
</application>
<!-- Declare Health Connect permissions for each data type you use -->
<!-- Read permissions -->
<uses-permission android:name="android.permission.health.READ_STEPS" />
<uses-permission android:name="android.permission.health.READ_WEIGHT" />
<uses-permission android:name="android.permission.health.READ_HEART_RATE" />
<!-- Add more read permissions... -->
<!-- Write permissions -->
<uses-permission android:name="android.permission.health.WRITE_STEPS" />
<uses-permission android:name="android.permission.health.WRITE_WEIGHT" />
<uses-permission android:name="android.permission.health.WRITE_HEART_RATE" />
<!-- Add more write permissions... -->
<!-- Feature permissions -->
<uses-permission android:name="android.permission.health.READ_HEALTH_DATA_IN_BACKGROUND" />
<uses-permission android:name="android.permission.health.READ_HEALTH_DATA_HISTORY" />
<!-- Add more feature permissions... -->
</manifest>
โ Important: You must declare a permission for each health data type and feature your app accesses. See the Health Connect data types list for all available permissions.
Step 2: Update MainActivity (Android 14+)
This SDK uses the modern registerForActivityResult API when requesting permissions from Health
Connect. For this to work correctly, your app's MainActivity must extend FlutterFragmentActivity
instead of FlutterActivity. This is required because registerForActivityResult is only available
in ComponentActivity and its subclasses.
Update android/app/src/main/kotlin/.../MainActivity.kt:
package com.example.yourapp
import io.flutter.embedding.android.FlutterFragmentActivity
class MainActivity : FlutterFragmentActivity() {
// Your existing code
}
Step 3: Enable AndroidX
Health Connect is built on AndroidX libraries. android.useAndroidX=true enables AndroidX support,
and android.enableJetifier=true automatically migrates third-party libraries to use AndroidX.
Update android/gradle.properties:
# Your existing configuration
android.enableJetifier=true
android.useAndroidX=true
Step 4: Set Minimum Android Version
Health Connect requires Android 8.0 (API 26) or higher. Update android/app/build.gradle:
android {
// Your existing configuration
defaultConfig {
// Your existing configuration
minSdkVersion 26 // Required for Health Connect
}
}
๐ iOS HealthKit Setup
Step 1: Configure Xcode
- Open your project in Xcode (
ios/Runner.xcworkspace) - Select your app target
- In General tab โ Set Minimum Deployments to 15.0
- In Signing & Capabilities tab โ Click + Capability โ Add HealthKit
Step 2: Update Info.plist
Add to ios/Runner/Info.plist:
<dict>
<!-- Existing keys -->
<!-- Required: Describe why your app reads health data -->
<key>NSHealthShareUsageDescription</key>
<string>This app needs to read your health data to provide personalized insights.</string>
<!-- Required: Describe why your app writes health data -->
<key>NSHealthUpdateUsageDescription</key>
<string>This app needs to save health data to track your progress.</string>
</dict>
โ ๏ธ Warning: Vague or generic usage descriptions may result in App Store rejection. Be specific about what data you access and why.
โก Quick Demo #
import 'package:health_connector/health_connector.dart';
Future<void> quickStart() async {
// 1. Check platform availability
final status = await HealthConnector.getHealthPlatformStatus();
if (status != HealthPlatformStatus.available) {
print('โ Health platform not available: $status');
return;
}
// 2. Create connector instance
final connector = await HealthConnector.create(
const HealthConnectorConfig(
loggerConfig: HealthConnectorLoggerConfig(
logProcessors: [PrintLogProcessor()],
),
),
);
// 3. Request permissions
final results = await connector.requestPermissions([
HealthDataType.steps.readPermission,
HealthDataType.steps.writePermission,
]);
// 4. Verify permissions were granted
final granted = results.every((r) => r.status != PermissionStatus.denied);
if (!granted) {
print('โ Permissions denied');
return;
}
// 5. Write health data
final now = DateTime.now();
final records = [
StepsRecord(
id: HealthRecordId.none,
startTime: now.subtract(Duration(hours: 3)),
endTime: now.subtract(Duration(hours: 2)),
count: Number(1500),
metadata: Metadata.automaticallyRecorded(
device: Device.fromType(DeviceType.phone),
),
),
StepsRecord(
id: HealthRecordId.none,
startTime: now.subtract(Duration(hours: 2)),
endTime: now.subtract(Duration(hours: 1)),
count: Number(2000),
metadata: Metadata.automaticallyRecorded(
device: Device.fromType(DeviceType.phone),
),
),
];
final recordIds = await connector.writeRecords(records);
print('โ๏ธ Wrote ${recordIds.length} records');
// 6. Read health data
final response = await connector.readRecords(
HealthDataType.steps.readInTimeRange(
startTime: now.subtract(Duration(days: 1)),
endTime: now,
),
);
print('๐ Found ${response.records.length} records:');
for (final record in response.records) {
print(' โ ${record.count.value} steps (${record.startTime}-${record.endTime})');
}
// 7. Aggregate health data
final totalSteps = await connector.aggregate(
HealthDataType.steps.aggregateSum(
startTime: now.subtract(Duration(days: 1)),
endTime: now,
),
);
print('โ Total steps: ${totalSteps.value.value}');
// 8. Delete health data
await connector.deleteRecords(
HealthDataType.steps.deleteByIds(recordIds),
);
print('๐๏ธ Deleted ${recordIds.length} records');
}
What's Next?
- Check out the Developer Guide for full API documentation, error handling, and advanced features.
- Check out the Supported Health Data Types.
๐ Developer Guide #
๐ Manage Permissions #
Check Permission Status
iOS Privacy: HealthKit purposefully restricts access to read authorization status to protect user privacy. The SDK explicitly exposes this platform behavior by returning
unknownfor all iOS read permissions. This is a native privacy feature, not an SDK limitation.
final status = await connector.getPermissionStatus(
HealthDataType.steps.readPermission,
);
switch (status) {
case PermissionStatus.granted:
print('โ
Steps read permission granted');
case PermissionStatus.denied:
print('โ Steps read permission denied');
case PermissionStatus.unknown:
print('โ Steps read permission unknown (iOS read)');
}
Workaround: Detecting iOS Read Status
Disclaimer: This workaround attempts to infer permission status, which bypasses HealthKit's intended privacy design. Use only if your app genuinely needs to determine read permission status.
Since iOS returns unknown for read permissions, you can infer the status by attempting a minimal
read operation. If the read fails with AuthorizationException, permission is definitively denied.
Future<bool> hasReadPermission(HealthDataType dataType) async {
try {
// Attempt to read a single record to check access
await connector.readRecords(
dataType.readInTimeRange(
startTime: DateTime.now().subtract(Duration(days: 1)),
endTime: DateTime.now(),
pageSize: 1, // Minimize data transfer
),
);
return true; // Read succeeded (or returned empty) -> Permission granted
} on AuthorizationException {
return false; // Explicitly denied
}
}
Request Permissions
// 1. Define permissions to request
final permissions = [
HealthDataType.steps.readPermission,
HealthDataType.steps.writePermission,
HealthDataType.weight.readPermission,
HealthPlatformFeature.readHealthDataInBackground.permission,
];
// 2. Request permissions
final results = await connector.requestPermissions(permissions);
// 3. Process results
for (final result in results) {
switch (result.status) {
case PermissionStatus.granted:
print('โ
${result.permission}');
case PermissionStatus.denied:
print('โ ${result.permission}');
case PermissionStatus.unknown:
print('โ ${result.permission} (iOS read permission)');
}
}
Get All Granted Permissions (Android Health Connect only)
iOS Privacy: HealthKit does not allow apps to enumerate granted permissions, preventing user fingerprinting. This API throws
UnsupportedOperationExceptionon iOS.
try {
final grantedPermissions = await connector.getGrantedPermissions();
for (final permission in grantedPermissions) {
print('โ
Granted: ${permission.dataType} (${permission.accessType})'); // Example: โ
Granted: HealthDataType.steps (read)
}
} on UnsupportedOperationException {
print('โน๏ธ Listing granted permissions is not supported on iOS');
}
Revoke All Permissions (Android Health Connect only)
iOS Privacy: HealthKit does not support programmatic permission revocation. Users must manage permissions in the iOS Settings app. This API throws
UnsupportedOperationExceptionon iOS.
try {
await connector.revokeAllPermissions();
print('๐ Permissions revoked');
} on UnsupportedOperationException {
print('โน๏ธ Programmatic revocation is not supported on iOS');
}
๐ Read Data #
Historical Data Access: Android Health Connect defaults to 30 daysโrequest
HealthPlatformFeature.readHealthDataHistorypermission for older data. iOS HealthKit has no restrictions for historical data access.
Read by ID
// 1. Define read request
final recordId = HealthRecordId('record-id');
final readRequest = HealthDataType.steps.readById(recordId)
// 2. Process read request
final record = await connector.readRecord(readRequest);
// 3. Process result
if (record != null) {
print('๐ Found: ${record.count.value} steps');
} else {
print('Not found record with ID: $recordId');
}
Read by Time Range
// 1. Define read request
final readRequest = HealthDataType.steps.readInTimeRange(
startTime: DateTime.now().subtract(Duration(days: 7)),
endTime: DateTime.now(),
);
// 2. Process read request
final response = await connector.readRecords(readRequest);
// 3. Process result
print('๐ Found ${response.records.length} records');
for (final record in response.records) {
print('${record.count.value} steps on ${record.startTime}');
}
Sort Records by Time
// Sort oldest first (ascending)
final oldestFirst = await connector.readRecords(
HealthDataType.steps.readInTimeRange(
startTime: DateTime.now().subtract(Duration(days: 7)),
endTime: DateTime.now(),
sortDescriptor: SortDescriptor.timeAscending,
),
);
// Sort newest first (descending) - default behavior
final newestFirst = await connector.readRecords(
HealthDataType.steps.readInTimeRange(
startTime: DateTime.now().subtract(Duration(days: 7)),
endTime: DateTime.now(),
sortDescriptor: SortDescriptor.timeDescending, // Default
),
);
Paginate Through All Records
// 1. Create read request with configured page size
var request = HealthDataType.steps.readInTimeRange(
startTime: DateTime.now().subtract(Duration(days: 30)),
endTime: DateTime.now(),
pageSize: 100,
);
// 2. Fetch all pages
final allRecords = <StepsRecord>[];
while (true) {
final response = await connector.readRecords(request);
allRecords.addAll(response.records.cast<StepsRecord>());
// Check if there are more pages
if (response.nextPageRequest == null) break;
request = response.nextPageRequest!;
}
// 3. Print total records
print('๐ Total: ${allRecords.length} records');
๐พ Write Data #
Write Single Record
// 1. Create record
final record = StepsRecord(
// `id` must be `HealthRecordId.none` for new records
id: HealthRecordId.none,
startTime: DateTime.now().subtract(Duration(hours: 1)),
endTime: DateTime.now(),
count: Number(5000),
metadata: Metadata.automaticallyRecorded(
device: Device.fromType(DeviceType.phone),
),
);
// 2. Write record
final recordId = await connector.writeRecord(record);
print('โ
Saved: $recordId');
Batch Write Multiple Records
final now = DateTime.now();
// 1. Create records
final records = [
StepsRecord(
id: HealthRecordId.none,
startTime: now.subtract(Duration(hours: 3)),
endTime: now.subtract(Duration(hours: 2)),
count: Number(1500),
metadata: Metadata.automaticallyRecorded(
device: Device.fromType(DeviceType.phone),
),
),
WeightRecord(
id: HealthRecordId.none,
time: now.subtract(Duration(hours: 1)),
weight: Mass.fromKilograms(70.5),
metadata: Metadata.automaticallyRecorded(
device: Device.fromType(DeviceType.phone),
),
),
HeightRecord(
id: HealthRecordId.none,
time: now,
height: Length.fromMeters(1.75),
metadata: Metadata.automaticallyRecorded(
device: Device.fromType(DeviceType.phone),
),
),
];
// 2. Write records (atomic operationโall succeed or all fail)
final ids = await connector.writeRecords(records);
print('โ
Wrote ${ids.length} records');
๐๏ธ Deleting Data #
Note: Apps can only delete records they createdโthis is a platform security restriction. Attempting to delete records created by other apps will throw an
AuthorizationException.
Delete by IDs
// 1. Define delete request
final request = HealthDataType.steps.deleteByIds([
HealthRecordId('id-1'),
HealthRecordId('id-2'),
]);
// 2. Delete specific steps records by IDs (atomic operationโall succeed or all fail)
await connector.deleteRecords(request);
print('โ
Deleted');
Delete by Time Range
// 1. Define delete request
final request = HealthDataType.steps.deleteInTimeRange(
startTime: DateTime.now().subtract(Duration(days: 7)),
endTime: DateTime.now(),
);
// 2. Delete all steps records created in the past week (atomic operationโall succeed or all fail)
await connector.deleteRecords(request);
๐ Update Data #
iOS Limitation: HealthKit uses an immutable data modelโrecords cannot be updated, only deleted and recreated. This is a platform security restriction.
Update Single Record (Android Health Connect only)
// 1. Fetch record to update
final record = await connector.readRecord(
HealthDataType.steps.readById(HealthRecordId('record-id')),
);
// 2. Update record value
await connector.updateRecord(
record.copyWith(count: Number(record.count.value + 500)),
);
print('โ
Record updated');
iOS Workaround: Delete + Recreate
// 1. Delete existing record
await connector.deleteRecords(
HealthDataType.steps.deleteByIds([existingRecord.id]),
);
// 2. Change record value
final newRecord = existingRecord.copyWith(
id: HealthRecordId.none,
count: Number(newValue),
);
// 3. Write new record with updated value
final newId = await connector.writeRecord(newRecord); // โ ๏ธ Note: ID changes after recreation
Batch Update (Android Health Connect only)
// 1. Fetch records to update
final response = await connector.readRecords(
HealthDataType.steps.readInTimeRange(
startTime: DateTime.now().subtract(Duration(days: 7)),
endTime: DateTime.now(),
),
);
// 2. Apply changes
final updated = response.records.map((r) =>
r.copyWith(count: Number(r.count.value + 100))
).toList();
// 3. Update records (atomic operationโall succeed or all fail)
await connector.updateRecords(updated);
print('โ
Updated ${updated.length} records');
โ Aggregate Data #
final now = DateTime.now();
final thirtyDaysAgo = now.subtract(Duration(days: 30));
// Calculate total steps for the past 30 days
final sumResult = await connector.aggregate(
HealthDataType.steps.aggregateSum(
startTime: thirtyDaysAgo,
endTime: now,
),
);
print('Total steps: ${sumResult.value}');
// Calculate average weight for the past 30 days
final avgResult = await connector.aggregate(
HealthDataType.weight.aggregateAvg(
startTime: thirtyDaysAgo,
endTime: now,
),
);
print('Average weight: ${avgResult.inKilograms} kg');
// Calculate minimum weight for the past 30 days
final minResult = await connector.aggregate(
HealthDataType.weight.aggregateMin(
startTime: thirtyDaysAgo,
endTime: now,
),
);
print('Minimum weight: ${minResult.inKilograms} kg');
// Calculate maximum weight for the past 30 days
final maxResult = await connector.aggregate(
HealthDataType.weight.aggregateMax(
startTime: thirtyDaysAgo,
endTime: now,
),
);
print('Maximum weight: ${maxResult.inKilograms} kg');
๐ Synchronize Data #
Synchronize Data is an incremental sync API that retrieves only health data that has changed since your last sync, dramatically reducing bandwidth usage and improving performance for apps that need to stay up-to-date with health data.
When to Use Sync vs Regular Reads
| Use Case | Recommended Approach |
|---|---|
| Periodic background sync (e.g., daily health data updates) | โ
Use synchronize() |
| Real-time monitoring of ongoing activity | โ
Use synchronize() |
| One-time data fetch for a specific time range | Use readRecords() |
| User-requested historical data (e.g., "show me last month") | Use readRecords() |
How Synchronization Works
Synchronization follows a two-phase flow:
-
Phase 1: Set Checkpoint (one-time setup)
- Call
synchronize()withsyncToken: null - This establishes a point-in-time marker (no data is returned)
- Save the returned
nextSyncTokenfor later use
- Call
-
Phase 2: Fetch Changes (repeated syncs)
- Call
synchronize()with your savedsyncToken - Receive only records that changed since that token was created
- Upserted records: New or updated records since last sync
- Deleted record IDs: Records that were deleted since last sync
- Always save the new
nextSyncTokento continue tracking changes
- Call
Example: Complete Sync Flow
import 'package:health_connector/health_connector.dart';
// Use SharedPreferences, secure storage, or your preferred persistence layer
final storage = LocalTokenStorage();
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// Step 1: Set Initial Checkpoint (run once per user/device)
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Future<void> setupSyncCheckpoint() async {
final connector = await HealthConnector.create();
// Pass null to establish "now" as the starting point
final result = await connector.synchronize(
dataTypes: [HealthDataType.steps, HealthDataType.heartRate],
syncToken: null, // ๐ null = set checkpoint
);
// No data returned at this stage
assert(result.upsertedRecords.isEmpty);
assert(result.deletedRecordIds.isEmpty);
// Save token for future syncs
await storage.saveToken(result.nextSyncToken.toJson());
print('โ
Sync checkpoint established');
}
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// Step 2: Fetch Changes Since Last Sync (run periodically)
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Future<void> syncHealthData() async {
final connector = await HealthConnector.create();
// Load saved token
final tokenJson = await storage.loadToken();
if (tokenJson == null) {
print('โ ๏ธ No checkpoint found. Run setupSyncCheckpoint() first.');
return;
}
final token = HealthDataSyncToken.fromJson(tokenJson);
// Fetch changes since the token was created
final result = await connector.synchronize(
dataTypes: [HealthDataType.steps, HealthDataType.heartRate],
syncToken: token, // ๐ Use saved token
);
print('๐ Sync results:');
print(' โข New/updated records: ${result.upsertedRecords.length}');
print(' โข Deleted record IDs: ${result.deletedRecordIds.length}');
// Process upserted records (new or modified)
for (final record in result.upsertedRecords) {
await database.upsert(record); // Update your local database
}
// Process deletions
for (final id in result.deletedRecordIds) {
await database.delete(id); // Remove from your local database
}
// โ ๏ธ CRITICAL: Always save the new token immediately
await storage.saveToken(result.nextSyncToken.toJson());
print('โ
Sync complete');
}
Handling Pagination
When there are many changes, results are paginated automatically. Use hasMore to detect
pagination and fetch all pages in a loop:
Future<void> syncAllPages() async {
final connector = await HealthConnector.create();
final tokenJson = await storage.loadToken();
if (tokenJson == null) {
print('โ ๏ธ No checkpoint found');
return;
}
var token = HealthDataSyncToken.fromJson(tokenJson);
final allUpsertedRecords = <HealthRecord>[];
final allDeletedRecordIds = <HealthRecordId>[];
// Fetch all pages until hasMore is false
do {
final result = await connector.synchronize(
dataTypes: [HealthDataType.steps],
syncToken: token,
);
allUpsertedRecords.addAll(result.upsertedRecords);
allDeletedRecordIds.addAll(result.deletedRecordIds);
// Update token for next page
token = result.nextSyncToken;
print('Fetched page with:');
print(' โข New/updated records: ${result.upsertedRecords.length}');
print(' โข Deleted record IDs: ${result.deletedRecordIds.length}');
} while (result.hasMore);
// Process all changes together
print('๐ Sync results:');
print(' โข New/updated records: ${allUpsertedRecords.length}');
print(' โข Deleted record IDs: ${allDeletedRecordIds.length}');
// Save the final token for the next synchronization
await storage.saveToken(token.toJson());
}
โ๏ธ Manage Features #
Check Feature Availability
final status = await connector.getFeatureStatus(
HealthPlatformFeature.readHealthDataInBackground,
);
if (status == HealthPlatformFeatureStatus.available) {
await connector.requestPermissions([
HealthPlatformFeature.readHealthDataInBackground.permission,
]);
print('โ
Feature available and requested');
} else {
print('โ Feature not availableโimplement fallback');
}
Note: All features are built directly into the OS and are always available. On Android, Health Connect features may vary depending on the installed app and Android version. Use
getFeatureStatus()to verify feature support on the user's device before requesting permissions.
โ ๏ธ Error Handling #
Every HealthConnectorException thrown by the SDK includes a HealthConnectorErrorCode that
provides specific details about what went wrong. Use this code to handle errors programmatically.
| Error Code | Exception Type | Platform | Description & Causes | Recovery Strategy |
|---|---|---|---|---|
permissionNotGranted |
AuthorizationException |
Both | Permission denied, revoked, or not determined. | Request permissions or guide user to settings. |
permissionNotDeclared |
ConfigurationException |
All | Missing required permission in AndroidManifest.xml or Info.plist. |
Developer Error: Add missing permissions to your app configuration. |
healthServiceUnavailable |
HealthServiceUnavailableException |
All | Device doesn't support Health Connect (Android) or HealthKit (iPad). | Check getHealthPlatformStatus(). Gracefully disable health features. |
healthServiceRestricted |
HealthServiceUnavailableException |
All | Health data access restricted by system policy (e.g. parental controls). | Gracefully disable health features and inform the user. |
healthServiceNotInstalledOrUpdateRequired |
HealthServiceUnavailableException |
Android | Health Connect app is missing or needs an update. | Prompt user to install/update via launchHealthAppPageInAppStore(). |
healthServiceDatabaseInaccessible |
HealthServiceException |
iOS | Device is locked and health database is encrypted/inaccessible. | Wait for device unlock or notify user to unlock their device. |
ioError |
HealthServiceException |
Android | Device storage I/O failed while reading/writing records. | Retry operation with exponential backoff. |
remoteError |
HealthServiceException |
Android | IPC communication with the underlying health service failed. | Retry operation; usually a temporary system glitch. |
rateLimitExceeded |
HealthServiceException |
Android | API request quota exhausted. | Wait and retry later. Implement exponential backoff. |
dataSyncInProgress |
HealthServiceException |
Android | Health Connect is currently syncing data; operations locked. | Retry after a short delay. |
invalidArgument |
InvalidArgumentException |
All | Invalid parameter, malformed record, or expired usage of a token. | Validate input. For expired sync tokens, restart sync with syncToken: null. |
unsupportedOperation |
UnsupportedOperationException |
All | The requested operation is not supported on the current platform or OS version (e.g. accessing Android-only data types on iOS). | Check @supportedOn annotations in documentation before using the API. |
unknownError |
UnknownException |
All | An unclassified internal system error occurred. | Log the error details for debugging. |
Example: Robust Error Handling
try {
await connector.writeRecord(record);
} on AuthorizationException catch (e) {
// Permission not granted.
print('๐ Authorization failed: ${e.message}');
} on HealthServiceUnavailableException catch (e) {
// Health Connect missing (Android) or device unsupported (iOS).
print('โ Service unavailable: ${e.code}');
if (e.code == HealthConnectorErrorCode.healthServiceNotInstalledOrUpdateRequired) {
// Android: Prompt user to install/update Health Connect
_promptToInstallHealthConnect();
} else {
// iOS/Android: Device capability missing. Disable health features.
_disableHealthIntegration();
}
} on HealthServiceException catch (e) {
switch (e.code) {
case HealthConnectorErrorCode.rateLimitExceeded:
// API quota exhausted. Wait and retry with backoff.
print('โณ Rate limit exceeded. Retrying in 5s...');
await Future.delayed(Duration(seconds: 5));
_retryWrite();
break;
case HealthConnectorErrorCode.dataSyncInProgress:
// Health Connect is busy syncing.
print('๐ Syncing... Retrying later...');
break;
case HealthConnectorErrorCode.remoteError:
case HealthConnectorErrorCode.ioError:
// Temporary system glitches. Retry once or twice.
print('๐ฅ Transient error: ${e.message}');
_retryWithBackoff();
break;
default:
print('โ ๏ธ Health Service Warning: ${e.message}');
break;
}
} on InvalidArgumentException catch (e) {
print('โ ๏ธ Invalid data or expired token: ${e.message}');
} catch (e, stack) {
print('โ๏ธ Unexpected system error: $e');
// reportToCrashlytics(e, stack);
}
๐ Logging #
Health data is sensitive, and user privacy is paramount. The Health Connector SDK adopts a strict zero-logging policy by default:
- No Internal Logging: The SDK never writes to
print,stdout, or platform logs ( Logcat/Console) on its own. - Full Control: You decide exactly where logs go. Even low-level logs from native Swift/Kotlin code are routed through to Dart, giving you a single control plane for all SDK activity.
- Compliance Ready: This architecture ensures no sensitive data is accidentally logged, making it easier to comply with privacy regulations (GDPR, HIPAA) and pass security reviews.
The system is configured via HealthConnectorLoggerConfig, where you define a list of
logProcessors. Each processor handles logs independently and asynchronously.
Setup with Built-in Processors
// Configure logging with built-in processors
final connector = await HealthConnector.create(
const HealthConnectorConfig(
loggerConfig: HealthConnectorLoggerConfig(
enableNativeLogging: false, // Optional: forward native Kotlin/Swift logs
logProcessors: [
// Print warnings and errors to console
PrintLogProcessor(
levels: [
HealthConnectorLogLevel.warning,
HealthConnectorLogLevel.error,
],
),
// Send all logs to dart:developer (integrates with DevTools)
DeveloperLogProcessor(
levels: HealthConnectorLogLevel.values,
),
],
),
),
);
Custom Processor Example
Create your own processor for custom logging needs:
// Example: File logging processor
class FileLogProcessor extends HealthConnectorLogProcessor {
final File logFile;
const FileLogProcessor({
required this.logFile,
super.levels = HealthConnectorLogLevel.values,
});
@override
Future<void> process(HealthConnectorLog log) async {
try {
final formatted = '${log.dateTime} [${log.level.name.toUpperCase()}] '
'${log.message}\n';
await logFile.writeAsString(formatted, mode: FileMode.append);
} catch (e) {
// Handle errors gracefully
debugPrint('Failed to write log: $e');
}
}
@override
bool shouldProcess(HealthConnectorLog log) {
// Custom filtering logic
return super.shouldProcess(log) &&
log.level == HealthConnectorLogLevel.error;
}
}
// Use custom processor
final connector = await HealthConnector.create(
HealthConnectorConfig(
loggerConfig: HealthConnectorLoggerConfig(
logProcessors: [
FileLogProcessor(logFile: File('/path/to/app.log')),
],
),
),
);
๐ References #
๐ Supported Health Data Types #
For a complete list of supported data types, please see Supported Health Data Types.
๐ Migration Guides #
- Migration Guide from
v1.x.xtov2.0.0 - Migration Guide from
v2.x.xtov3.0.0
๐ค Contributing #
Contributions are welcome! See our GitHub Issues to report bugs or request features.
๐ License #
This project is licensed under the Apache 2.0 License - see the LICENSE file for details.