> ## Documentation Index
> Fetch the complete documentation index at: https://openwearables.io/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Flutter Health Data SDK

> Flutter SDK for background sync from Apple HealthKit, Samsung Health, and Health Connect. Cross-platform Dart API wrapping the native iOS and Android SDKs.

## Introduction

The Open Wearables Flutter SDK (`open_wearables_health_sdk`) enables secure background synchronization of health data from **Apple HealthKit** (iOS), **Samsung Health**, and **Health Connect** (Android) to the Open Wearables platform.

On iOS, the Flutter SDK is a **wrapper around the [native iOS SDK](https://openwearables.io/docs/sdk/ios.md)** (`OpenWearablesHealthSDK`). On Android, it wraps the **[native Android SDK](https://openwearables.io/docs/sdk/android.md)** (`open_wearables_android_sdk`). This means all the core sync logic — background execution, streaming uploads, secure storage, and retry mechanisms — is handled by the native implementations under the hood. The Flutter layer provides a convenient Dart API for cross-platform apps.

> [card] [Flutter SDK Repository](https://github.com/the-momentum/open_wearables_health_sdk)
>
> View source code, report issues, and contribute to the Flutter SDK.

> [card] [Native iOS SDK](https://openwearables.io/docs/sdk/ios.md)
>
> See the native iOS SDK documentation for the underlying iOS implementation.

> [card] [Native Android SDK](https://openwearables.io/docs/sdk/android.md)
>
> See the native Android SDK documentation for the underlying Android implementation.

## Features

* **Cross-Platform** - Single Dart API for iOS (HealthKit) and Android (Samsung Health, Health Connect)
* **Background Sync** - Health data syncs even when your app is in the background
* **Incremental Updates** - Only syncs new data using anchored queries
* **Secure Storage** - Credentials stored in iOS Keychain / Android EncryptedSharedPreferences
* **Dual Authentication** - Token-based auth with auto-refresh or API key authentication
* **Resumable Sessions** - Sync sessions survive app restarts
* **Wide Data Support** - Steps, heart rate, workouts, sleep, and 40+ data types
* **Provider Selection** - Choose between Samsung Health and Health Connect on Android

## Requirements

> [tab] iOS
>
> | Requirement | Details |
> | - | - |
> | iOS Version | iOS 15.0+ |
> | Xcode | Xcode 14+ |
> | Apple Developer Account | Required for HealthKit entitlement |
> | HealthKit Capability | Must be enabled in Xcode |
> | Physical Device | HealthKit doesn't work in iOS Simulator |

> [tab] Android
>
> | Requirement | Details |
> | - | - |
> | Min SDK | Android 10 (API 29+) |
> | Samsung Health SDK | For Samsung Health provider |
> | Health Connect | For Health Connect provider |
> | Permissions | See Android configuration below |

> [tab] Flutter
>
> | Requirement | Details |
> | - | - |
> | Flutter | 3.3.0+ |
> | Dart SDK | 3.9.2+ |

## Installation

**1. Add the dependency**

Add `open_wearables_health_sdk` to your `pubspec.yaml`:

```yaml theme={null}
dependencies:
  open_wearables_health_sdk: ^0.0.25
```

Then run:

```bash theme={null}
flutter pub get
```

**2. iOS Configuration**

Add the following to your `ios/Runner/Info.plist`:

```xml theme={null}
<!-- Health data permission -->
<key>NSHealthShareUsageDescription</key>
<string>This app syncs your health data to your account.</string>

<!-- Background modes for sync -->
<key>UIBackgroundModes</key>
<array>
    <string>fetch</string>
    <string>processing</string>
</array>

<!-- Background task identifiers -->
<key>BGTaskSchedulerPermittedIdentifiers</key>
<array>
    <string>com.openwearables.healthsdk.task.refresh</string>
    <string>com.openwearables.healthsdk.task.process</string>
</array>
```

Then enable HealthKit capability in Xcode:

1. Open `ios/Runner.xcworkspace` in Xcode
2. Select your target → **Signing & Capabilities**
3. Click **+ Capability** → Add **HealthKit**
4. Check **Background Delivery** if you want updates while app is closed

**3. Android Configuration**

The SDK's Android module handles most configuration automatically. Make sure your `android/app/build.gradle` has:

```groovy theme={null}
android {
    compileSdk 36
    defaultConfig {
        minSdk 29
    }
}
```

No additional permissions or manifest entries are needed — the SDK's `AndroidManifest.xml` merges automatically.

## Quick Start

Here's the minimal code to get health sync working:

```dart theme={null}
import 'package:open_wearables_health_sdk/open_wearables_health_sdk.dart';

class HealthService {
  Future<void> initialize() async {
    // 1. Configure the SDK with your backend host
    await OpenWearablesHealthSdk.configure(
      host: 'https://api.openwearables.io',
    );

    // 2. Check if already signed in (session restored from secure storage)
    if (OpenWearablesHealthSdk.isSignedIn) {
      print('Session restored for ${OpenWearablesHealthSdk.currentUser?.userId}');
      return;
    }

    // 3. Get credentials from YOUR backend
    final credentials = await yourBackend.getHealthCredentials();

    // 4. Sign in with the SDK
    await OpenWearablesHealthSdk.signIn(
      userId: credentials.userId,
      accessToken: credentials.accessToken,
      refreshToken: credentials.refreshToken,
    );

    // 5. Request health permissions
    await OpenWearablesHealthSdk.requestAuthorization(
      types: [
        HealthDataType.steps,
        HealthDataType.heartRate,
        HealthDataType.sleep,
        HealthDataType.workout,
      ],
    );

    // 6. Start background sync (sync last 90 days of data)
    await OpenWearablesHealthSdk.startBackgroundSync(syncDaysBack: 90);
  }
}
```

## Android Provider Selection

On Android, you need to select a health data provider before requesting permissions:

```dart theme={null}
import 'dart:io';

if (Platform.isAndroid) {
  // Check available providers
  final providers = await OpenWearablesHealthSdk.getAvailableProviders();
  for (final p in providers) {
    print('${p.displayName} (${p.id})');
  }

  // Set the provider (samsung or google/Health Connect)
  await OpenWearablesHealthSdk.setProvider(AndroidHealthProvider.healthConnect);
}
```

> [!NOTE]
>
> `AndroidHealthProvider.samsungHealth` maps to Samsung Health, and `AndroidHealthProvider.healthConnect` maps to Google Health Connect. Use `getAvailableProviders()` to check which are installed on the device.

## Log Level

Control SDK log output with `setLogLevel`. The default is `OWLogLevel.debug` (logs only in debug builds):

```dart theme={null}
// Always show logs (useful for troubleshooting in production)
await OpenWearablesHealthSdk.setLogLevel(OWLogLevel.always);

// Disable all logs
await OpenWearablesHealthSdk.setLogLevel(OWLogLevel.none);
```

| Level | Description |
| - | - |
| `OWLogLevel.none` | No logs at all |
| `OWLogLevel.always` | Logs are always printed regardless of build mode |
| `OWLogLevel.debug` | Logs are printed only in debug builds (default) |

## Listening to Events

The SDK exposes streams for logging and auth errors:

```dart theme={null}
import 'package:open_wearables_health_sdk/open_wearables_health_sdk.dart';

// Log stream from native SDK
MethodChannelOpenWearablesHealthSdk.logStream.listen((message) {
  print('[HealthSDK] $message');
});

// Auth error stream (e.g. 401 responses)
MethodChannelOpenWearablesHealthSdk.authErrorStream.listen((error) {
  print('Auth error: ${error['statusCode']} - ${error['message']}');
});
```

## Documentation

> [card] [Integration Guide](https://openwearables.io/docs/sdk/flutter/integration.md)
>
> Complete guide to integrating the SDK including authentication flow, backend setup, and best practices.

> [card] [Troubleshooting](https://openwearables.io/docs/sdk/flutter/troubleshooting.md)
>
> Common issues and their solutions for iOS and Android.

## Supported Health Data Types

The SDK supports 40+ health data types across multiple categories:

> [accordion] Activity & Fitness
>
> | Type | Description |
> | - | - |
> | `steps` | Step count |
> | `distanceWalkingRunning` | Walking/running distance |
> | `distanceCycling` | Cycling distance |
> | `flightsClimbed` | Floors climbed |
> | `walkingSpeed` | Average walking speed |
> | `walkingStepLength` | Step length |
> | `walkingAsymmetryPercentage` | Walking asymmetry percentage |
> | `walkingDoubleSupportPercentage` | Walking double support percentage |
> | `sixMinuteWalkTestDistance` | 6-minute walk test |
> | `activeEnergy` | Active energy burned |
> | `basalEnergy` | Basal (resting) energy burned |

> [accordion] Running & Cycling
>
> | Type | Description |
> | - | - |
> | `runningPower` | Running power (iOS 16+). On Android, reads power for any activity |
> | `runningVerticalOscillation` | Running vertical oscillation (iOS 16+, iOS only) |
> | `runningGroundContactTime` | Running ground contact time (iOS 16+, iOS only) |
> | `cyclingSpeed` | Cycling speed (iOS 17+). On Android, reads speed for any activity |
> | `cyclingPower` | Cycling power (iOS 17+). On Android, reads power for any activity |
> | `cyclingCadence` | Cycling cadence (iOS 17+) |
> | `cyclingFunctionalThresholdPower` | Cycling functional threshold power (iOS 17+, iOS only) |

> [accordion] Heart & Vitals
>
> | Type | Description |
> | - | - |
> | `heartRate` | Heart rate measurements |
> | `restingHeartRate` | Resting heart rate |
> | `heartRateVariabilitySDNN` | HRV (SDNN) |
> | `vo2Max` | VO2 max |
> | `oxygenSaturation` | Blood oxygen |
> | `respiratoryRate` | Breathing rate |

> [accordion] Body Measurements
>
> | Type | Description |
> | - | - |
> | `bodyMass` | Weight |
> | `height` | Height |
> | `bmi` | Body Mass Index |
> | `bodyFatPercentage` | Body fat % |
> | `leanBodyMass` | Lean body mass |
> | `waistCircumference` | Waist circumference |
> | `bodyTemperature` | Body temperature |

> [accordion] Blood & Metabolic
>
> | Type | Description |
> | - | - |
> | `bloodGlucose` | Blood glucose level |
> | `insulinDelivery` | Insulin delivery |
> | `bloodPressureSystolic` | Systolic blood pressure |
> | `bloodPressureDiastolic` | Diastolic blood pressure |
> | `bloodPressure` | Blood pressure (correlation type) |

> [accordion] Sleep & Mindfulness
>
> | Type | Description |
> | - | - |
> | `sleep` | Sleep sessions and stages |
> | `mindfulSession` | Meditation/mindfulness sessions |

> [accordion] Reproductive Health
>
> | Type | Description |
> | - | - |
> | `menstrualFlow` | Menstrual flow |
> | `cervicalMucusQuality` | Cervical mucus quality |
> | `ovulationTestResult` | Ovulation test result |
> | `sexualActivity` | Sexual activity |

> [accordion] Nutrition
>
> | Type | Description |
> | - | - |
> | `dietaryEnergyConsumed` | Calories consumed |
> | `dietaryCarbohydrates` | Carbs |
> | `dietaryProtein` | Protein |
> | `dietaryFatTotal` | Total fat |
> | `dietaryWater` | Water intake |

> [accordion] Workouts
>
> | Type | Description |
> | - | - |
> | `workout` | All workout types with metadata |
> | `workoutEffortScore` | Workout effort rated by the user (iOS 18+, iOS only) |
> | `estimatedWorkoutEffortScore` | Workout effort estimated by Apple Watch (iOS 18+, iOS only) |

> [accordion] Aliases
>
> | Type | Alias For |
> | - | - |
> | `restingEnergy` | `basalEnergy` (iOS only) |
> | `bloodOxygen` | `oxygenSaturation` (iOS only) |

> [!NOTE]
>
> Not all data types are available on all providers. Samsung Health supports a subset of types compared to Health Connect and HealthKit. See the [Android SDK docs](https://openwearables.io/docs/sdk/android.md) for provider-specific availability.

## Next Steps

> [card] [Integration Guide](https://openwearables.io/docs/sdk/flutter/integration.md)
>
> Complete step-by-step integration guide.

> [card] [API Reference](https://github.com/the-momentum/open_wearables_health_sdk)
>
> Full API documentation on GitHub.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.