> For the complete documentation index, see [llms.txt](https://docs.tryterra.co/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.tryterra.co/mobile-sdks/flutter-sdk-2.md). Agents can also search and read this documentation through its [MCP server](https://docs.tryterra.co/~gitbook/mcp).

# Flutter SDK

Install terra\_flutter\_bridge 2.x, connect Apple Health, Health Connect or Samsung Health, and keep their data flowing to Terra in the background.

This page shows how to use `terra_flutter_bridge` 2.x to connect Apple Health on iOS, and Health Connect or Samsung Health on Android: install the package, create the client, connect a user and set up background delivery.

The Dart API is the same as the [React Native SDK](https://docs.tryterra.co/mobile-sdks/react-native-sdk-2.md)'s. Both packages run on the same native bridge over the iOS and Android SDKs.

{% hint style="info" %}
This page covers `terra_flutter_bridge` 2.x (2.2.1 and later on pub.dev). For the 1.x plugin, published as the 0.x versions of the same package, read [Flutter SDK 1.x](https://docs.tryterra.co/mobile-sdks/flutter.md).
{% endhint %}

## Before you begin

* Flutter 3.24 or later, with Dart 3.5 or later.
* iOS 15 or later.
* Android `minSdk` 28, `compileSdk` 36, Kotlin 2.0 or later and Android Gradle Plugin 8.9.1 or later.
* A backend endpoint that mints Terra auth tokens. See [Generate an auth token](#generate-an-auth-token).

## Install the SDK

1. Add the [`terra_flutter_bridge` package](https://pub.dev/packages/terra_flutter_bridge) to your app:

{% code title="pubspec.yaml" %}

```yaml
dependencies:
  terra_flutter_bridge: ^2.3.2
```

{% endcode %}

The package carries the iOS SDK and resolves the Android SDK from Maven Central, so there is nothing else to install.

On iOS, Flutter builds the plugin with Swift Package Manager or CocoaPods, whichever your app uses. Swift Package Manager is on by default from Flutter 3.44, and you can turn it on in earlier versions with `flutter config --enable-swift-package-manager`. It needs `terra_flutter_bridge` 2.3.2 or later; earlier versions build through CocoaPods even when Swift Package Manager is on. You do not need to change your Podfile or Xcode project either way, because Flutter adds the plugin on the next build.

2. Complete the following iOS and/or Android setup. The native client is built at app launch, before any Dart runs, because a background sync never starts a Flutter engine.

{% tabs %}
{% tab title="iOS Setup" %}

1. **Add Capabilities** in **Signing & Capabilities**:
   1. HealthKit > HealthKit Background Delivery
   2. Background Modes > Background fetch
2. **Add the following keys to your Info.plist:**

{% code title="ios/Runner/Info.plist" lineNumbers="true" %}

```xml
<key>TerraDevID</key>
<string>YOUR_DEV_ID</string>
<key>NSHealthShareUsageDescription</key>
<string>We read your health data to show your activity and sleep.</string>
<key>NSHealthUpdateUsageDescription</key>
<string>We save your workouts to Apple Health.</string>
<key>UIBackgroundModes</key>
<array>
  <string>fetch</string>
</array>
<key>BGTaskSchedulerPermittedIdentifiers</key>
<array>
  <string>co.tryterra.sdk.refresh</string>
</array>
```

{% endcode %}

`TerraDevID` is your **Developer ID** provided by Terra. `NSHealthUpdateUsageDescription` is required even if your app never writes: App Store Connect rejects the upload without it.

3. **Bootstrap the SDK at launch.** Call `TerraFlutterBridgePlugin.bootstrap()` first in `application(_:didFinishLaunchingWithOptions:)`, before `super`. Keep the plugin registration your Flutter template already has:

{% code title="ios/Runner/AppDelegate.swift" lineNumbers="true" %}

```swift
import Flutter
import UIKit
import terra_flutter_bridge

override func application(
  _ application: UIApplication,
  didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
  TerraFlutterBridgePlugin.bootstrap()
  // ... your template's plugin registration, unchanged
  return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
```

{% endcode %}

{% hint style="info" %}
`bootstrap()` reads `TerraDevID` from `Info.plist`, builds the client and registers background sync. iOS only accepts a background task registered before launch finishes, and a HealthKit wake starts your app without a Flutter engine.

Without it, every call fails with `bridge.not_bootstrapped`, and the error's `details['line']` names the line to add.
{% endhint %}
{% endtab %}

{% tab title="Android Setup" %}

1. **Add your Developer ID** inside `<application>`:

{% code title="android/app/src/main/AndroidManifest.xml" lineNumbers="true" %}

```xml
<meta-data
  android:name="co.tryterra.sdk.DEV_ID"
  android:value="YOUR_DEV_ID" />
```

{% endcode %}

There is no code to add. The package's `androidx.startup` initializer builds the client before `Application.onCreate`. If your app removes WorkManager's default initializer to configure WorkManager itself, call `TerraFlutter.bootstrap(this)` at the end of `Application.onCreate` instead.

2. **Make `MainActivity` a `FlutterFragmentActivity`.** The Health Connect permission sheet is launched through an activity result, which a plain `FlutterActivity` cannot register for. With `FlutterActivity`, `permissions.request` fails with `bridge.no_activity`.

{% code title="android/app/src/main/kotlin/.../MainActivity.kt" lineNumbers="true" %}

```kotlin
import io.flutter.embedding.android.FlutterFragmentActivity

class MainActivity : FlutterFragmentActivity()
```

{% endcode %}

3. **Declare the Health Connect permissions.** Add one `<uses-permission>` for each Health Connect type your `permissions.request` reads. For `read: [DataCategory.activity, DataCategory.daily, DataCategory.sleep]`:

{% code title="android/app/src/main/AndroidManifest.xml" lineNumbers="true" %}

```xml
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.health.READ_HEART_RATE" />
<uses-permission android:name="android.permission.health.READ_RESTING_HEART_RATE" />
<uses-permission android:name="android.permission.health.READ_HEART_RATE_VARIABILITY" />
<uses-permission android:name="android.permission.health.READ_STEPS" />
<uses-permission android:name="android.permission.health.READ_SLEEP" />
<uses-permission android:name="android.permission.health.READ_EXERCISE" />
<uses-permission android:name="android.permission.health.READ_ACTIVE_CALORIES_BURNED" />
<uses-permission android:name="android.permission.health.READ_TOTAL_CALORIES_BURNED" />
<uses-permission android:name="android.permission.health.READ_BASAL_METABOLIC_RATE" />
<uses-permission android:name="android.permission.health.READ_DISTANCE" />
<uses-permission android:name="android.permission.health.READ_FLOORS_CLIMBED" />
<uses-permission android:name="android.permission.health.READ_ELEVATION_GAINED" />
<uses-permission android:name="android.permission.health.READ_POWER" />
<uses-permission android:name="android.permission.health.READ_SPEED" />
<uses-permission android:name="android.permission.health.READ_OXYGEN_SATURATION" />
<uses-permission android:name="android.permission.health.READ_RESPIRATORY_RATE" />
<uses-permission android:name="android.permission.health.READ_HEALTH_DATA_IN_BACKGROUND" />
<uses-permission android:name="android.permission.health.READ_HEALTH_DATA_HISTORY" />

<queries>
  <package android:name="com.google.android.apps.healthdata" />
</queries>
```

{% endcode %}

{% hint style="warning" %}
Health Connect refuses the whole permission sheet if the request asks for one type the manifest does not declare. The [Android SDK guide](https://docs.tryterra.co/mobile-sdks/android-sdk-2.md) lists the types behind every category.
{% endhint %}

4. **Add the permission rationale.** Health Connect links to your privacy policy from its permission screen. Add the rationale filter to your main activity, and the alias that Android 14 and later require:

{% code title="android/app/src/main/AndroidManifest.xml" lineNumbers="true" %}

```xml
<activity android:name=".MainActivity" android:exported="true">
  <!-- ... your existing filters ... -->
  <intent-filter>
    <action android:name="androidx.health.ACTION_SHOW_PERMISSIONS_RATIONALE" />
  </intent-filter>
</activity>

<activity-alias
  android:name=".ViewPermissionUsageActivity"
  android:exported="true"
  android:targetActivity=".MainActivity"
  android:permission="android.permission.START_VIEW_PERMISSION_USAGE">
  <intent-filter>
    <action android:name="android.intent.action.VIEW_PERMISSION_USAGE" />
    <category android:name="android.intent.category.HEALTH_PERMISSIONS" />
  </intent-filter>
</activity-alias>
```

{% endcode %}

{% hint style="warning" %}
Without the alias, Android 14 and later refuse every read.
{% endhint %}

5. **Samsung Health (optional).** To read Samsung Health directly, follow [Samsung Health](https://docs.tryterra.co/mobile-sdks/samsung-health.md), set `terraSamsungHealth=true` in `android/gradle.properties`, and add Samsung's `samsung-health-data-api.aar` to your app. No Terra artifact carries it.
   {% endtab %}
   {% endtabs %}

## Initialize the SDK

### Import the Terra SDK

{% code lineNumbers="true" %}

```dart
import 'package:terra_flutter_bridge/terra_flutter_bridge.dart';
```

{% endcode %}

### Create the Terra client

Call [`createTerra()`](https://docs.tryterra.co/reference/mobile-sdks/flutter-sdk-2#createterra) once, at app start, with a token provider that fetches a token from your backend:

{% code title="main.dart" lineNumbers="true" %}

```dart
import 'package:flutter/material.dart';
import 'package:terra_flutter_bridge/terra_flutter_bridge.dart';

late final Terra terra;

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  terra = createTerra(tokenProvider: () => api.fetchTerraToken());
  runApp(const MyApp());
}
```

{% endcode %}

`createTerra` attaches to the native client your app built at launch. It does not build a second one. The token provider is called only while `connect` makes a new link.

## Connect a user

Once the client exists, create a connection by calling `connect()`, then request permissions with `permissions.request()` to show the permission screen.

### Call `connect()`

Call [`connect()`](https://docs.tryterra.co/reference/mobile-sdks/flutter-sdk-2#connect) with the following arguments:

* `source`: `Source.health` (Apple Health on iOS, Health Connect on Android) or `Source.samsungHealth` (Samsung Health directly, Android only).
* `endUser`: The person the connection is for. `EndUser.reference(id: id)` with the same value your backend sends as `reference_id`, or `const EndUser.anonymous()` if your backend sends none.
* `token` (optional): A token you already hold, for example from a QR code or a deep link. A token passed this way always creates a fresh link.

### Call `permissions.request()`

Call [`permissions.request()`](https://docs.tryterra.co/reference/mobile-sdks/flutter-sdk-2#permissions.request) with the categories to read and write. The categories are `activity`, `body`, `daily`, `sleep`, `nutrition` and `menstruation`, and `athlete` on iOS. `connect` never shows a permission screen on its own.

{% tabs %}
{% tab title="Apple Health and Health Connect" %}
{% code title="connect.dart" lineNumbers="true" %}

```dart
Future<void> connectHealth(String userId) async {
  try {
    await terra.connect(Source.health, EndUser.reference(id: userId));
    final granted = await terra.permissions.request(read: [
      DataCategory.activity,
      DataCategory.body,
      DataCategory.daily,
      DataCategory.sleep,
    ]);
    debugPrint('Granted: $granted');
  } on TerraError catch (error) {
    debugPrint('Connection failed: ${error.code.wire}');
  }
}
```

{% endcode %}
{% endtab %}

{% tab title="Samsung Health (Android)" %}
Follow [Samsung Health](https://docs.tryterra.co/mobile-sdks/samsung-health.md) first, then set `terraSamsungHealth=true` in `android/gradle.properties`.

{% code title="connect.dart" lineNumbers="true" %}

```dart
await terra.connect(Source.samsungHealth, EndUser.reference(id: userId));
await terra.permissions.request(
  read: [DataCategory.daily, DataCategory.sleep],
  source: Source.samsungHealth,
);
```

{% endcode %}

Without `terraSamsungHealth=true`, `Source.samsungHealth` fails with `health_data_unavailable`. To read Samsung Health's data through Health Connect instead, connect `Source.health`, once the person lets Samsung Health share with Health Connect.
{% endtab %}
{% endtabs %}

### What `permissions.request()` returns

* **Android**: what the sheet granted, narrowed to this call. Check it rather than assuming the person said yes.
* **iOS**: `null`. iOS never reveals whether a read was granted.

When the request reads anything, the Android sheet also asks for background read and history read, if your manifest declares them. Check them afterwards with `terra.permissions.backgroundReadStatus?.call()` and `terra.permissions.historyReadStatus?.call()`.

{% hint style="info" %}
**Heart rate needs `body` on iOS.** Heart rate is uploaded on the daily route. On iOS its permission comes with `body`, so request `body` to upload it. On Android it comes with `daily`.
{% endhint %}

### Request individual types

A category asks for everything behind it: `body` is blood glucose, blood pressure and temperature as well as weight. If your consent screen and `NSHealthShareUsageDescription` name specific data, ask for exactly those types with `readTypes`. This needs SDK 2.3.0 or later.

{% code title="connect.dart" lineNumbers="true" %}

```dart
await terra.permissions.request(readTypes: [
  HealthDataType.workouts,
  HealthDataType.activeEnergy,
  HealthDataType.distance,
  HealthDataType.steps,
  HealthDataType.heartRate,
  HealthDataType.sleepAnalysis,
  HealthDataType.weight,
]);

final status = await terra.permissions.typeStatus(HealthDataType.heartRate);
```

{% endcode %}

The sheet names exactly those types. From then on the install is type-scoped:

* The SDK reads and uploads only the requested types, plus every type of a category you also asked for whole. A type you never requested is never read.
* A payload leaves out the fields of types you did not request. They are absent, not zero. A daily payload carries only the requested day totals. A workout carries its energy, distance and steps only when `activeEnergy`, `distance` and `steps` are requested too.
* The upload does not say which types you requested, so request every type the payloads you rely on need.
* On iOS, a category your app only writes is not read back. Android never reads one back.
* Types join everything requested before, so a later request adds to them.

An app that never passes `readTypes` keeps the category behaviour.

* `workoutRoute`, `speed`, `power` and `cyclingCadence` need `workouts`, or `activity` asked for whole. Without either, the request fails with `workouts_required`.
* A type the platform has no store type for fails with `bridge.unsupported_on_platform`, and nothing is recorded. For example, `exerciseTime` and `bmi` are iOS only, so leave them out of the Android request.
* `Source.samsungHealth` is asked by category only. Any `readTypes` for it fails with `bridge.unsupported_on_platform`.
* `typeStatus` answers `notDisclosed` on iOS, because HealthKit never reports a read decision. On Android it answers `granted` once any permission behind the type is granted.

{% hint style="warning" %}
**Moving from categories to types on Android.** Health Connect's `sleep` category also asks for heart rate, resting heart rate, heart rate variability, oxygen saturation and respiratory rate. Replacing `DataCategory.sleep` with `HealthDataType.sleepAnalysis` alone stops reading them. Add `heartRate`, `restingHeartRate`, `heartRateVariability`, `oxygenSaturation` and `respiratoryRate` to keep them.
{% endhint %}

The [Permissions reference](https://docs.tryterra.co/reference/mobile-sdks/permissions-mapping#individual-types) lists every type with the HealthKit and Health Connect types behind it. On Android, declare the Health Connect permissions for the types you request.

### Request Apple Health Records

Apple Health Records are opt-in and iOS only. They are never part of `permissions.request`. This needs SDK 2.3.0 or later. Before you ask:

1. Have Health Records (`CLINICAL_RECORD`) enabled for your Terra client. Until then, Terra refuses the uploads with `data_type_not_enabled`.
2. Add `health-records` to the `com.apple.developer.healthkit.access` entitlement.
3. Add `NSHealthClinicalHealthRecordsShareUsageDescription` to your Info.plist, beside `NSHealthShareUsageDescription`.

Then ask on HealthKit's own sheet. The member is `null` on Android:

{% code title="connect.dart" lineNumbers="true" %}

```dart
await terra.permissions.requestClinicalRecords?.call();
```

{% endcode %}

Clinical records go to Terra only. No local read returns them.

### The same person keeps their link

A stored link is restored only for the person it was made for. A normal launch for the same person restores it with no network call and never calls `tokenProvider`. When someone else signs in on the same phone, the SDK retires the old link and links again, so their data does not arrive under the first person's `reference_id`.

## Generate an auth token

`tokenProvider` needs a **single-use token** to link the device to Terra. It is called only while `connect` makes a new link: the first time the device links, after a reinstall, when a different person connects, or when Terra no longer accepts the device's key.

Generate the token with `POST https://api.tryterra.co/v2/auth/generateAuthToken` from **your backend server**, with your Terra `x-api-key` and `dev-id` in the headers and your own user identifier as `reference_id`. Then return it to your app from your own API.

{% code title="Your backend" %}

```bash
curl --request POST \
  --url 'https://api.tryterra.co/v2/auth/generateAuthToken?reference_id=<YOUR_USER_ID>' \
  --header 'dev-id: <YOUR_DEV_ID>' \
  --header 'x-api-key: <YOUR_API_KEY>'
```

{% endcode %}

{% hint style="warning" %}

* Tokens expire after three minutes and are spent on first use.
* **DO NOT** expose your API key in your mobile app. Make this call **only** from your **backend**.
  {% endhint %}

## Validate the connection

To check that a connection is still working on the client side, use [`diagnostics.state()`](https://docs.tryterra.co/reference/mobile-sdks/flutter-sdk-2#diagnostics). `terra.connections()` lists the connections on the device, with the `userId` of each.

{% code title="status.dart" lineNumbers="true" %}

```dart
final state = await terra.diagnostics.state();
final last = await terra.diagnostics.lastDelivery();
final events = terra.diagnostics.events().listen((event) => debugPrint('$event'));

if (state is DiagnosticsStateLinkRevoked) {
  await terra.connect(Source.health, EndUser.reference(id: userId));
}
```

{% endcode %}

{% hint style="info" %}
**Always validate the connection on app start.** If `diagnostics.state()` is `DiagnosticsStateLinkRevoked`, Terra stopped accepting this device's key. Call `connect` again with the same end user to link again.

`diagnostics.events()` reports everything the SDK does as it happens, and never carries a health value. Cancel the subscription to stop listening.
{% endhint %}

## Set up background delivery

Background delivery allows data to be synced even when your app is not brought to the foreground. There is no call that starts a sync: after the permission sheet is answered, the SDK uploads on its own, in the foreground and in the background.

{% tabs %}
{% tab title="Apple Health" %}
Background sync is registered by `TerraFlutterBridgePlugin.bootstrap()` from [Install the SDK](#install-the-sdk). Check that:

1. `bootstrap()` runs in `didFinishLaunchingWithOptions`, before `super`.
2. `co.tryterra.sdk.refresh` is in `BGTaskSchedulerPermittedIdentifiers`.
3. The HealthKit Background Delivery capability is on.

`terra.background.isRegistered()` answers whether it was registered.
{% endtab %}

{% tab title="Android (Health Connect & Samsung)" %}
Background sync is scheduled through WorkManager by the package's startup initializer. Keep WorkManager's default initializer, or call `TerraFlutter.bootstrap(this)` at the end of `Application.onCreate`.

Declare `READ_HEALTH_DATA_IN_BACKGROUND` in your manifest so the permission sheet asks for background read. `terra.background.isRegistered()` answers whether background sync was registered.
{% endtab %}
{% endtabs %}

From here, health data events reach your data destination, such as a webhook, automatically.

You can also [request historical data](https://docs.tryterra.co/unified-api/requesting-historical-data.md) from your backend to backfill.

Check out the [Flutter SDK reference](https://docs.tryterra.co/reference/mobile-sdks/flutter-sdk-2) for details about all the functions in the SDK.

## Read and write on the device

Local reads go straight to the health store and never touch the network:

{% code title="reads.dart" lineNumbers="true" %}

```dart
final heartRate = await terra.body.heartRate(const TimeRange.lastDays(days: 7));
final steps = await terra.daily.steps(const TimeRange.lastDays(days: 7));
final sleep = await terra.sleep.segments(const TimeRange.lastDays(days: 1));
final workouts = await terra.activity.workouts(const TimeRange.lastHours(hours: 24));
```

{% endcode %}

These reads return more of what the store holds:

| Read                    | Returns                                                                                                                                          | Category       |
| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ | -------------- |
| `daily.totals`          | The store's own total for each local day: distances, active and basal energy, flights climbed and, on iOS, exercise minutes                      | `daily`        |
| `daily.intraday`        | The energy, distance and floors records those totals are made of                                                                                 | `daily`        |
| `body.restingHeartRate` | The store's resting heart rate, one per day. On Android, request `daily` as well                                                                 | `body`         |
| `body.readings`         | Weight, height, BMI (iOS), body fat, lean mass, HRV, VO2 max, blood pressure, blood glucose, oxygen saturation, temperature and respiratory rate | `body`         |
| `activity.routes`       | Each workout's GPS track                                                                                                                         | `activity`     |
| `activity.intensity`    | Speed, power and cycling cadence                                                                                                                 | `activity`     |
| `nutrition.quantities`  | One value per nutrient, not grouped into meals                                                                                                   | `nutrition`    |
| `nutrition.hydration`   | Water, one sample per drink                                                                                                                      | `nutrition`    |
| `menstruation.flow`     | One flow value per logged day                                                                                                                    | `menstruation` |
| `menstruation.events`   | Ovulation tests, cervical mucus and intermenstrual bleeding                                                                                      | `menstruation` |
| `athlete?.profile()`    | iOS only. Biological sex, date of birth, wheelchair use and move mode                                                                            | `athlete`      |

Request the category before you read it. A read of a category your app never requested fails with `authorization_not_determined`. [`terra.availability()`](https://docs.tryterra.co/reference/mobile-sdks/flutter-sdk-2#availability) answers whether the device can serve the store at all. It needs no connection, so you can call it before `connect`.

{% code title="reads.dart" lineNumbers="true" %}

```dart
if (await terra.availability() is! StoreAvailabilityAvailable) return;

final totals = await terra.daily.totals(const TimeRange.lastDays(days: 7));
final readings = await terra.body.readings(const TimeRange.lastDays(days: 30));
final profile = await terra.athlete?.profile();
```

{% endcode %}

To write data your app measured itself:

{% code title="writes.dart" lineNumbers="true" %}

```dart
final ids = await terra.activity.log([
  WorkoutEntry(
    start: DateTime.now().subtract(const Duration(minutes: 30)),
    end: DateTime.now(),
    activity: const WorkoutActivity.running(),
    totalDistanceMeters: 5000,
  ),
]);
await terra.activity.delete(ids.first);
```

{% endcode %}

The write namespaces are `activity`, `body`, `daily`, `nutrition` and `sleep`. `log` returns one ID per entry, which is the only handle for deleting it later.

## Disconnect a user

{% code lineNumbers="true" %}

```dart
await terra.disconnect();
```

{% endcode %}

`disconnect` forgets the link on the device and tells Terra to stop accepting its key. To remove the user from Terra, call [deauthenticateUser](https://docs.tryterra.co/reference/health-and-fitness-api/authentication#delete-auth-deauthenticateuser) from your backend.

## Handle errors

Every failure is a `TerraError` with a stable `code`, a `retryable` flag, and a `details` map:

{% code lineNumbers="true" %}

```dart
try {
  await terra.connect(Source.health, EndUser.reference(id: userId));
} on TerraError catch (error) {
  if (error.code == TerraErrorCode.tokenRejected) {
    // mint a fresh token and try again
  }
}
```

{% endcode %}

The [Flutter SDK reference](https://docs.tryterra.co/reference/mobile-sdks/flutter-sdk-2#error-codes) lists every code and which platform raises it.

## Troubleshooting

| Symptom                                                                                | Cause                                                                                                                                                     | Fix                                                                                                                                                 |
| -------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- |
| Every call fails with `bridge.not_bootstrapped`                                        | iOS: `TerraFlutterBridgePlugin.bootstrap()` is missing or `TerraDevID` is not in `Info.plist`. Android: the `co.tryterra.sdk.DEV_ID` meta-data is missing | Add the line named in `details['line']`                                                                                                             |
| `permissions.request` fails with `bridge.no_activity` (Android)                        | `MainActivity` extends `FlutterActivity`, or no activity was on screen                                                                                    | Extend `FlutterFragmentActivity`, and request permissions while your app is in the foreground                                                       |
| `connect` fails with `bridge.token_timeout` (iOS) or `token_provider_failed` (Android) | `tokenProvider` did not answer within `tokenTimeout`, or it failed                                                                                        | Check your token endpoint. Pass a longer `tokenTimeout` to `createTerra` if it is slow                                                              |
| `connect` fails with `token_rejected`                                                  | The token expired (three minutes) or was already used                                                                                                     | Mint a fresh token for every link                                                                                                                   |
| `permissions.request` fails with `workouts_required`                                   | `readTypes` names `workoutRoute`, `speed`, `power` or `cyclingCadence` without `workouts`                                                                 | Add `HealthDataType.workouts` to the request                                                                                                        |
| `permissions.request` fails with `bridge.unsupported_on_platform`                      | `readTypes` names a type this platform has no store type for, or asks Samsung Health for types                                                            | Request only the types the platform has. Ask Samsung Health by category                                                                             |
| The Android sheet closes without asking                                                | The request reads a type the manifest does not declare                                                                                                    | Declare every Health Connect type the request reads                                                                                                 |
| Workouts arrive without energy or distance                                             | The install is type-scoped and did not request `activeEnergy` or `distance`                                                                               | Add the types the payloads need to `readTypes`                                                                                                      |
| `diagnostics.state()` is `DiagnosticsStateLinkRevoked`                                 | Terra stopped accepting this device's key                                                                                                                 | Call `connect` again with the same end user                                                                                                         |
| `background.isRegistered()` is `false`                                                 | The native bootstrap did not run at launch                                                                                                                | iOS: call `bootstrap()` in `didFinishLaunchingWithOptions`. Android: keep WorkManager's default initializer, or call `TerraFlutter.bootstrap(this)` |

{% hint style="info" %}
**The mobile SDKs are only for Apple Health, Health Connect and Samsung Health.** These have no web API, so your app reads them on the phone and sends the data to Terra. Every other provider connects through the [Unified API](https://docs.tryterra.co/unified-api/getting-started) with no SDK.
{% endhint %}

## Next steps

* [Planned workouts on Apple Watch](https://docs.tryterra.co/mobile-sdks/planned-workouts-apple-watch.md): put plans on the user's Watch from iOS.
* [Health data events](https://docs.tryterra.co/unified-api/receiving-data-updates.md): handle the data the SDK uploads.
* [Historical data requests](https://docs.tryterra.co/unified-api/requesting-historical-data.md): backfill beyond the first sync.
