> ## 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 Integration Guide

> Integrate the Flutter SDK for health data sync on iOS and Android. Covers backend auth, SDK setup, sign-in, and HealthKit or Health Connect permissions.

## Overview

This guide walks you through the complete integration of the Open Wearables Flutter SDK, from backend setup to production deployment.

**1. Set up backend authentication endpoint**

**2. Configure the SDK in your Flutter app**

**3. Implement sign-in flow**

**4. Request health permissions**

**5. Start background sync**

> [!NOTE]
>
> Read the [Mobile SDK Integration Guide](https://openwearables.io/docs/sdk/integration.md) first. It covers what is the same on every platform: authentication, the backend token endpoint, the SDK lifecycle, and the production checklist. This page shows the Flutter code for each step.

## Step 1: Backend Setup

Your backend exchanges your app credentials for user-scoped SDK tokens and forwards them to the app - the app never sees `app_id` / `app_secret`. See [Backend Endpoint](https://openwearables.io/docs/sdk/integration.md#backend-endpoint) for the setup and example code.

## Step 2: SDK Configuration

Configure the SDK once at app startup, typically in your main initialization code.

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

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  
  // Configure SDK with your backend host - this also restores any existing session
  await OpenWearablesHealthSdk.configure(
    host: 'https://api.openwearables.io',
  );
  
  runApp(MyApp());
}
```

### Configuration Options

| Parameter | Type | Description |
| - | - | - |
| `host` | `String` | **Required.** The Open Wearables API base URL — host only, without path suffix (e.g. `https://api.openwearables.io`) |

> [!NOTE]
>
> Provide only the base host URL, e.g. `https://your-domain.com`. Do **not** append `/api/v1/` or any other path — the SDK adds the required path prefix automatically.

```dart theme={null}
// For self-hosted Open Wearables
await OpenWearablesHealthSdk.configure(
  host: 'https://your-domain.com',
);
```

### Session Restoration

The SDK automatically restores the user session from secure storage when `configure()` is called:

```dart theme={null}
await OpenWearablesHealthSdk.configure(host: 'https://api.openwearables.io');

// Check if user was previously signed in
if (OpenWearablesHealthSdk.isSignedIn) {
  print('Welcome back, ${OpenWearablesHealthSdk.currentUser?.userId}!');
  // User is already signed in, can start sync directly
} else {
  // Need to sign in first
}
```

## Step 3: Sign In

After getting credentials from your backend, sign in with the SDK:

> [!NOTE]
>
> The `userId` parameter is the **Open Wearables User ID** (UUID) — the `id` returned by the [Create User](https://openwearables.io/docs/api-reference/external:-users/create-user.md) endpoint. Do **not** pass your own `external_user_id` here.

### Token-Based Authentication (Recommended)

```dart theme={null}
Future<void> connectHealth() async {
  try {
    // 1. Get tokens from YOUR backend (e.g. https://api.yourapp.com)
    final response = await yourApi.post('/api/health/connect');
    final credentials = json.decode(response.body);
    
    // 2. Sign in with the SDK
    final user = await OpenWearablesHealthSdk.signIn(
      userId: credentials['userId'],
      accessToken: credentials['accessToken'],
      refreshToken: credentials['refreshToken'],
    );
    
    print('Connected: ${user.userId}');
  } on SignInException catch (e) {
    print('Sign-in failed: ${e.message} (status: ${e.statusCode})');
  }
}
```

### API Key Authentication

For simpler setups (e.g. internal tools), you can use API key authentication directly:

```dart theme={null}
final user = await OpenWearablesHealthSdk.signIn(
  userId: 'user123',
  apiKey: 'your_api_key',
);
```

> [!WARNING]
>
> API key authentication embeds the key in the app. Only use this for internal or trusted applications. For production apps, always use token-based authentication.

### Automatic Token Refresh

When you provide a `refreshToken`, the SDK automatically handles 401 responses by refreshing the access token and retrying the request.

You can also update tokens manually:

```dart theme={null}
await OpenWearablesHealthSdk.updateTokens(
  accessToken: newAccessToken,
  refreshToken: newRefreshToken,
);
```

## Step 4: Request Permissions

Request access to specific health data types:

```dart theme={null}
Future<bool> requestHealthPermissions() async {
  final authorized = await OpenWearablesHealthSdk.requestAuthorization(
    types: [
      HealthDataType.steps,
      HealthDataType.heartRate,
      HealthDataType.restingHeartRate,
      HealthDataType.sleep,
      HealthDataType.workout,
      HealthDataType.activeEnergy,
      HealthDataType.bodyMass,
    ],
  );
  
  if (authorized) {
    print('Health permissions granted');
  } else {
    print('Some permissions were denied');
  }
  
  return authorized;
}
```

### Android Provider Selection

On Android, you must select a health data provider before requesting authorization:

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

Future<AndroidHealthProvider> selectAndroidProvider() async {
  final prefs = await SharedPreferences.getInstance();
  final savedProvider = prefs.getString('health_provider');

  // Restore previously chosen provider if still available
  final providers = await OpenWearablesHealthSdk.getAvailableProviders();

  if (savedProvider != null) {
    final restored = providers.cast<AndroidHealthProvider?>().firstWhere(
      (p) => p?.name == savedProvider,
      orElse: () => null,
    );
    if (restored != null) return restored;
  }

  // Prefer Health Connect, fall back to Samsung Health
  final AndroidHealthProvider chosen;
  if (providers.contains(AndroidHealthProvider.healthConnect)) {
    chosen = AndroidHealthProvider.healthConnect;
  } else if (providers.contains(AndroidHealthProvider.samsungHealth)) {
    chosen = AndroidHealthProvider.samsungHealth;
  } else {
    throw Exception(
      'No supported health provider found. '
      'Please install Health Connect or Samsung Health.',
    );
  }

  await prefs.setString('health_provider', chosen.name);
  return chosen;
}

// Usage
if (Platform.isAndroid) {
  final provider = await selectAndroidProvider();
  await OpenWearablesHealthSdk.setProvider(provider);
}

// Then request authorization
final authorized = await OpenWearablesHealthSdk.requestAuthorization(
  types: [
    HealthDataType.steps,
    HealthDataType.heartRate,
    HealthDataType.sleep,
    HealthDataType.workout,
    HealthDataType.activeEnergy,
  ],
);
print('Permissions granted: $authorized');
```

> [!NOTE]
>
> On iOS, users can grant partial permissions. The SDK will sync whatever data the user allows.

> [!TIP]
>
> Request only the data types you actually need. Requesting too many types can overwhelm users and reduce acceptance rates.

## Step 5: Start Background Sync

Enable background sync to keep data flowing even when your app is in the background:

```dart theme={null}
await OpenWearablesHealthSdk.startBackgroundSync();

// Check sync status
print('Sync active: ${OpenWearablesHealthSdk.isSyncActive}');
```

### Controlling Sync History Depth

By default, the SDK syncs all available historical data on the first sync. Use the `syncDaysBack` parameter to limit how far back the sync goes:

```dart theme={null}
// Sync only the last 90 days of data
await OpenWearablesHealthSdk.startBackgroundSync(syncDaysBack: 90);

// Sync last 30 days
await OpenWearablesHealthSdk.startBackgroundSync(syncDaysBack: 30);

// Full sync — all available history (default)
await OpenWearablesHealthSdk.startBackgroundSync();
```

| Parameter | Type | Default | Description |
| - | - | - | - |
| `syncDaysBack` | `int?` | `null` | Number of days of historical data to sync. Syncs from the start of the day that many days ago. When `null`, syncs all available history. The value is persisted and used for subsequent background syncs until changed. |

### Background Sync Behavior

> [tab] iOS
>
> | Mechanism | Frequency |
> | - | - |
> | HealthKit Observer Queries | Immediate on new data |
> | BGAppRefreshTask | Every \~15 minutes (system-managed) |
> | BGProcessingTask | Network-required background processing |

> [tab] Android
>
> | Mechanism | Frequency |
> | - | - |
> | WorkManager | Periodic sync with foreground service |
> | Foreground Service | Used during active sync for reliability |

> [!WARNING]
>
> Background sync frequency is managed by the OS and may vary based on battery level, network conditions, and user behavior.

### Log Level

Control SDK log output using `setLogLevel`. By default, the SDK uses `OWLogLevel.debug`, which prints logs only in debug builds:

```dart theme={null}
// Always show logs (including release builds)
await OpenWearablesHealthSdk.setLogLevel(OWLogLevel.always);

// Only show logs in debug builds (default)
await OpenWearablesHealthSdk.setLogLevel(OWLogLevel.debug);

// 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) |

> [!TIP]
>
> Set `OWLogLevel.always` during development or when troubleshooting sync issues in production. Switch to `OWLogLevel.none` if you want to suppress all SDK output.

## Complete Integration Example

Here's a complete service class showing the full integration:

```dart theme={null}
import 'dart:convert';
import 'dart:io';
import 'package:open_wearables_health_sdk/open_wearables_health_sdk.dart';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';

class HealthSyncService {
  final String _backendUrl;
  final String _authToken;

  HealthSyncService({
    required String backendUrl,
    required String authToken,
  })  : _backendUrl = backendUrl,
        _authToken = authToken;

  /// Initialize the health sync service
  Future<void> initialize() async {
    // Set up event listeners
    MethodChannelOpenWearablesHealthSdk.logStream.listen((message) {
      print('[HealthSync] $message');
    });

    MethodChannelOpenWearablesHealthSdk.authErrorStream.listen((error) {
      print('[HealthSync] Auth error: ${error['statusCode']}');
    });

    await OpenWearablesHealthSdk.configure(
      host: 'https://api.openwearables.io',
    );

    // Enable logs in all builds for debugging (default is debug-only)
    await OpenWearablesHealthSdk.setLogLevel(OWLogLevel.always);
  }

  /// Get current status
  OpenWearablesHealthSdkStatus get status => OpenWearablesHealthSdk.status;
  bool get isConnected => OpenWearablesHealthSdk.isSignedIn;
  bool get isSyncing => OpenWearablesHealthSdk.isSyncActive;

  /// Connect health data for the current user
  Future<void> connect() async {
    switch (OpenWearablesHealthSdk.status) {
      case OpenWearablesHealthSdkStatus.signedIn:
        if (!OpenWearablesHealthSdk.isSyncActive) {
          await _startSync();
        }
        return;

      case OpenWearablesHealthSdkStatus.configured:
        await _signIn();
        await _startSync();
        return;

      case OpenWearablesHealthSdkStatus.notConfigured:
        throw Exception('SDK not configured. Call initialize() first.');
    }
  }

  Future<void> _signIn() async {
    // Call YOUR backend — not the Open Wearables API directly
    final response = await http.post(
      Uri.parse('$_backendUrl/api/health/connect'),
      headers: {
        'Authorization': 'Bearer $_authToken',
        'Content-Type': 'application/json',
      },
    );

    if (response.statusCode != 200) {
      throw Exception('Failed to get health credentials');
    }

    final data = json.decode(response.body);

    await OpenWearablesHealthSdk.signIn(
      userId: data['userId'],
      accessToken: data['accessToken'],
      refreshToken: data['refreshToken'],
    );
  }

  Future<void> _startSync() async {
    if (Platform.isAndroid) {
      final providers = await OpenWearablesHealthSdk.getAvailableProviders();

      final prefs = await SharedPreferences.getInstance();
      final savedName = prefs.getString('health_provider');

      // Restore saved provider or pick the best available one
      AndroidHealthProvider? chosen;
      if (savedName != null) {
        chosen = providers.cast<AndroidHealthProvider?>().firstWhere(
          (p) => p?.name == savedName,
          orElse: () => null,
        );
      }
      chosen ??= providers.contains(AndroidHealthProvider.healthConnect)
          ? AndroidHealthProvider.healthConnect
          : providers.contains(AndroidHealthProvider.samsungHealth)
              ? AndroidHealthProvider.samsungHealth
              : null;

      if (chosen == null) {
        throw Exception(
          'No supported health provider available on this device. '
          'Please install Health Connect or Samsung Health.',
        );
      }

      await prefs.setString('health_provider', chosen.name);
      await OpenWearablesHealthSdk.setProvider(chosen);
    }

    final authorized = await OpenWearablesHealthSdk.requestAuthorization(
      types: [
        HealthDataType.steps,
        HealthDataType.heartRate,
        HealthDataType.sleep,
        HealthDataType.workout,
        HealthDataType.activeEnergy,
      ],
    );

    if (!authorized) {
      throw Exception('Health permissions not granted');
    }

    await OpenWearablesHealthSdk.startBackgroundSync(syncDaysBack: 90);
  }

  /// Disconnect health data
  Future<void> disconnect() async {
    await OpenWearablesHealthSdk.stopBackgroundSync();
    await OpenWearablesHealthSdk.signOut();
  }

  /// Check for interrupted sync sessions
  Future<void> checkAndResumeSync() async {
    final status = await OpenWearablesHealthSdk.getSyncStatus();
    
    if (status['hasResumableSession'] == true) {
      print('Resuming interrupted sync...');
      print('Already sent: ${status['sentCount']} records');
      await OpenWearablesHealthSdk.resumeSync();
    }
  }

  /// Re-sync the last 90 days (syncDaysBack: 0 for the full history)
  Future<void> resyncAllData() async {
    await OpenWearablesHealthSdk.stopBackgroundSync();
    await OpenWearablesHealthSdk.resetAnchors();
    await OpenWearablesHealthSdk.startBackgroundSync(syncDaysBack: 90);
  }
}
```

### Using the Service

```dart theme={null}
class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  late HealthSyncService _healthService;

  @override
  void initState() {
    super.initState();
    _initializeHealth();
  }

  Future<void> _initializeHealth() async {
    _healthService = HealthSyncService(
      backendUrl: 'https://api.yourapp.com',
      authToken: await getAuthToken(),
    );

    await _healthService.initialize();
    
    // Check for interrupted syncs
    await _healthService.checkAndResumeSync();
  }

  Future<void> _connectHealth() async {
    try {
      await _healthService.connect();
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('Health connected!')),
      );
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('Failed: $e')),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: ElevatedButton(
          onPressed: _connectHealth,
          child: Text(_healthService.isConnected 
            ? 'Health Connected' 
            : 'Connect Health'),
        ),
      ),
    );
  }
}
```

## Data Sync Endpoint

The SDK sends health data to:

**host** `string` *required*

Your Open Wearables API base URL (e.g. `https://api.example.com`).

**userId** `string` *required*

The user ID returned when registering the SDK user.

```bash theme={null}
POST {host}/api/v1/sdk/users/{userId}/sync
```

Data is automatically normalized to the Open Wearables unified data model and can be accessed through the standard API endpoints.

## Next Steps

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

> [card] [Data Types](https://openwearables.io/docs/architecture/data-types.md)
>
> Available health metrics and data formats.


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