> ## 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.

# Open Wearables Flutter Example App

> Explore the Flutter SDK with a working example app. Syncs Apple Health and Android health data in minutes. Good for personal tracking or coach app builds.

## Overview

The SDK repository includes a fully functional example app that demonstrates how to use SDK to sync Apple Health and Android health data with Open Wearables. It's also a great way for individuals to sync their personal health data and get it into Open Wearables in minutes! Use it to test the SDK, explore the code, and see how everything works together.

<Card title="Example App Source" icon="github" href="https://github.com/the-momentum/open_wearables_health_sdk/tree/main/example">
  View the example app source code on GitHub.
</Card>

<Info>
  Don't want to build the app yourself? Join our [Discord](https://discord.gg/qrcfFnNE6H) and ask for a **TestFlight** beta invitation. The app will also be available in the App Store soon!
</Info>

## What You'll See

The example app demonstrates the complete integration flow:

1. **Invitation Code** - Connect via invitation code (host + code → redeem → sign in)
2. **SDK Configuration** - Initialize the SDK with proper host settings
3. **Authentication** - Sign in with credentials from the dashboard
4. **Provider Selection** - On Android, choose between Samsung Health and Health Connect
5. **Permission Request** - Request health data permissions from the user
6. **Background Sync** - Enable automatic health data synchronization
7. **Sync Status** - Monitor sync progress and handle interruptions
8. **Log Viewer** - Browse SDK logs with search

<Card title="See the full flow in action" icon="play" href="/app/introduction#see-it-in-action">
  Watch how data flows from device setup through syncing to the dashboard and API.
</Card>

## Running the Example App

<Steps>
  <Step title="Clone the repository">
    ```bash theme={null}
    git clone https://github.com/the-momentum/open_wearables_health_sdk.git
    cd open_wearables_health_sdk/example
    ```
  </Step>

  <Step title="Install dependencies">
    ```bash theme={null}
    flutter pub get
    ```
  </Step>

  <Step title="iOS Setup">
    Open `ios/Runner.xcworkspace` in Xcode and:

    1. Select your development team in **Signing & Capabilities**
    2. Ensure **HealthKit** capability is enabled
    3. Update the bundle identifier if needed
  </Step>

  <Step title="Android Setup (optional)">
    For Android:

    1. Ensure Health Connect is installed on the device (or Samsung Health for Samsung devices)
    2. No additional Xcode/Android Studio configuration needed
  </Step>

  <Step title="Get credentials from Open Wearables Dashboard">
    1. Go to your Open Wearables dashboard
    2. Create a new user or select an existing one
    3. Generate an invitation code for the user
    4. Copy the invitation code and host URL
  </Step>

  <Step title="Run the app">
    ```bash theme={null}
    flutter run
    ```

    <Note>
      For iOS: Run on a **physical iOS device** - HealthKit doesn't work in the simulator.
      For Android: Run on a device or emulator with Health Connect installed.
    </Note>
  </Step>

  <Step title="Connect and sync">
    1. Enter the host URL and invitation code
    2. Tap **Connect** to redeem the code and sign in
    3. On Android, select a health provider (Samsung Health or Health Connect)
    4. Grant health permissions when prompted
    5. Tap **Start Sync** to begin background synchronization
    6. Check the dashboard to see your health data appear!
  </Step>
</Steps>

## Example App Code Structure

The example app demonstrates best practices for SDK integration:

```
example/
├── lib/
│   └── main.dart          # Main app with SDK integration
├── ios/
│   └── Runner/
│       └── Info.plist     # HealthKit permissions & background modes
├── android/
│   └── app/
│       └── src/main/
│           └── AndroidManifest.xml
└── pubspec.yaml           # Dependencies
```

### Key Code Sections

**SDK Initialization:**

```dart theme={null}
await OpenWearablesHealthSdk.configure(
  host: hostUrl,
);
```

**Sign In (via invitation code):**

```dart theme={null}
// Redeem invitation code to get credentials
final response = await http.post(
  Uri.parse('$host/api/v1/sdk/invitation-codes/$code/redeem'),
);
if (response.statusCode != 200) {
  throw Exception('Invitation redeem failed: ${response.statusCode}');
}
final data = json.decode(response.body);

// Sign in with returned credentials
await OpenWearablesHealthSdk.signIn(
  userId: data['user_id'],
  accessToken: data['access_token'],
  refreshToken: data['refresh_token'],
);
```

**Provider Selection (Android):**

```dart theme={null}
if (Platform.isAndroid) {
  final providers = await OpenWearablesHealthSdk.getAvailableProviders();
  if (providers.isEmpty) {
    throw Exception('No Android health provider is available');
  }
  final selectedProvider = providers.contains(AndroidHealthProvider.healthConnect)
      ? AndroidHealthProvider.healthConnect
      : providers.first;
  await OpenWearablesHealthSdk.setProvider(selectedProvider);
}
```

**Request Permissions:**

```dart theme={null}
await OpenWearablesHealthSdk.requestAuthorization(
  types: [
    HealthDataType.steps,
    HealthDataType.heartRate,
    HealthDataType.sleep,
    HealthDataType.workout,
    // ... more types
  ],
);
```

**Start Background Sync:**

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

**Log Stream:**

```dart theme={null}
MethodChannelOpenWearablesHealthSdk.logStream.listen((message) {
  // Display in logs page
});
```

## Testing the Full Flow

<Steps>
  <Step title="Set up Open Wearables locally (optional)">
    If you want to test with a local instance:

    ```bash theme={null}
    git clone https://github.com/the-momentum/open-wearables.git
    cd open-wearables
    docker compose up -d
    ```

    Then use your local URL as the host when connecting in the app.
  </Step>

  <Step title="Create test data">
    **iOS:** Add some health data to Apple Health on your device:

    * Open the Health app
    * Browse → Steps → Add Data
    * Add a few data points

    **Android:** Add data via Health Connect or Samsung Health.
  </Step>

  <Step title="Trigger sync and verify">
    1. In the example app, tap **Sync Now**
    2. Check the Open Wearables dashboard
    3. Your health data should appear under the user's timeseries!
  </Step>
</Steps>

## Troubleshooting the Example App

<AccordionGroup>
  <Accordion title="App crashes on launch (iOS)">
    Make sure you're running on a **physical device**, not the simulator. HealthKit is not available in the iOS Simulator.
  </Accordion>

  <Accordion title="Sign-in fails">
    * Verify your invitation code is correct and hasn't been used already
    * Check that the host URL is the API URL (not the dashboard URL)
    * Check that your Open Wearables instance is running
    * Ensure network connectivity
  </Accordion>

  <Accordion title="No data syncing">
    * Confirm health permissions were granted (check iOS Settings → Privacy → Health, or Android Settings → Health Connect)
    * Make sure there's actual health data in Apple Health / Health Connect
    * Try tapping **Sync Now** to trigger an immediate sync
    * Check the Logs page in the app for errors
  </Accordion>

  <Accordion title="Xcode signing errors (iOS)">
    * Select your development team in Xcode
    * Update the bundle identifier to something unique
    * Ensure your Apple Developer account has HealthKit capability
  </Accordion>

  <Accordion title="Provider not available (Android)">
    * For Health Connect: ensure it's installed from Play Store (pre-installed on Android 14+)
    * For Samsung Health: only available on Samsung devices with Samsung Health installed
  </Accordion>
</AccordionGroup>

## Next Steps

<CardGroup cols={2}>
  <Card title="Integration Guide" icon="book" href="/sdk/flutter/integration">
    Integrate the SDK into your own app.
  </Card>

  <Card title="Troubleshooting" icon="wrench" href="/sdk/flutter/troubleshooting">
    Common issues and solutions.
  </Card>
</CardGroup>
