> 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/streaming-api/flutter.md).

# Flutter SDK

Connect a BLE wearable or Apple Watch to your Flutter app with terra\_flutter\_rt, then stream its data to Terra.

## Install the SDK

1. Add [`terra_flutter_rt`](https://pub.dev/packages/terra_flutter_rt) to your `pubspec.yaml`:

```yaml
dependencies:
  terra_flutter_rt: ^X.X.X
```

2. **iOS:** In your `Info.plist`, add:
   * `Privacy - Bluetooth Always Usage Description`: Justification for BLE usage
   * `Privacy - Motion Usage Description`: Justification for motion sensor usage (required if streaming accelerometer, gyroscope, or step data from the phone's built-in sensors via `Connection.apple`)
3. **Android:** Permissions are requested automatically by the SDK on initialization.

## Initialize the SDK

{% hint style="info" %}
Initialize the SDK every time the app is opened or brought into the foreground.
{% endhint %}

```dart
import 'package:terra_flutter_rt/terra_flutter_rt.dart';
import 'package:terra_flutter_rt/types.dart';

await TerraFlutterRt.init('YOUR_DEV_ID', 'YOUR_REFERENCE_ID');
```

## Register the phone

Register the phone with Terra using an authentication token generated **from your backend**:

```dart
final token = 'yourAuthToken'; // Generated from your backend

await TerraFlutterRt.initConnection(token);
```

{% hint style="warning" %}
Call `initConnection` on every cold start, after `init` and before scanning. The connection lives for the current app session only and is not persisted, so a full app kill clears it. Skipping this after a restart (calling only `init`) leaves scanning with no active connection, which on iOS renders `iOSScanView` as a blank screen. Each call needs a fresh token, as auth tokens are single-use.
{% endhint %}

To generate the **token**, make the below call **from your backend**:

{% openapi src="<https://raw.githubusercontent.com/tryterra/openapi/refs/heads/master/dist/core/v2-bundled.yaml>" path="/auth/generateAuthToken" method="post" %}
<https://raw.githubusercontent.com/tryterra/openapi/refs/heads/master/dist/core/v2-bundled.yaml>
{% endopenapi %}

## Scan for devices

Two approaches depending on your needs:

### Use the built-in scan widget

On Android, this shows a native device picker. On iOS, use the `iOSScanView` widget.

```dart
import 'package:terra_flutter_rt/ios_controller.dart';

// Android: shows native picker
await TerraFlutterRt.startDeviceScan(
  Connection.ble,
  connectionCallback: (connected) {
    print('Device connected: $connected');
  },
);

// iOS: embed the native BLE scanner view in your widget tree
// (renders empty Container on Android)
iOSScanView()
```

### Scan programmatically

Discover devices one by one and connect manually:

```dart
await TerraFlutterRt.startDeviceScanToCallback(
  Connection.ble,
  (Device device) async {
    print('Found: ${device.deviceName}');
    // Connect to this device
    await TerraFlutterRt.connectDevice(device);
  },
  connectionCallback: (connected) {
    print('Connection status: $connected');
  },
);
```

## Start streaming

Once a device is connected, start streaming data to your app via a callback:

```dart
void onUpdate(Update data) {
  print('${data.type.datatypeString}: ${data.val}');
}

await TerraFlutterRt.startRealtimeToApp(
  Connection.ble,
  [DataType.heartRate, DataType.steps],
  onUpdate,
);
```

To stream to Terra's server instead, see [Stream to Terra](#stream-to-terra).

## Stop streaming and disconnect

```dart
await TerraFlutterRt.stopRealtime(Connection.ble);
await TerraFlutterRt.disconnect(Connection.ble);
```

## Stream from an Apple Watch

To stream data from an Apple Watch:

```dart
// Connect to paired Apple Watch (iOS only: returns false on Android)
final connected = await TerraFlutterRt.connectWatchOS();

if (connected) {
  // Start receiving watch data
  await TerraFlutterRt.startRealtimeToApp(
    Connection.watchOs,
    [DataType.heartRate],
    onUpdate,
  );
}
```

{% hint style="info" %}
The watchOS app itself must be written in native Swift using the `Terra` class from the `TerraRTiOS` framework. See the [iOS SDK page](https://docs.tryterra.co/streaming-api/ios-swift.md#stream-from-an-apple-watch) for the watch-side setup.
{% endhint %}

You can also control workout sessions on the watch from your Flutter app:

```dart
await TerraFlutterRt.resumeWatchOSWorkout();
await TerraFlutterRt.pauseWatchOSWorkout();
await TerraFlutterRt.stopWatchOSWorkout();
```

## Stream to Terra

Once data from the wearable reaches your app, you can send it to Terra's websocket server. Your backend then receives it through a [backend consumer](https://docs.tryterra.co/streaming-api/terra-greater-than-your-backend.md).

The [local stream](#start-streaming) uses `startRealtimeToApp`. To send data to Terra's server instead, use `startRealtimeToServer` with a **streaming token**:

```dart
import 'package:terra_flutter_rt/terra_flutter_rt.dart';
import 'package:terra_flutter_rt/types.dart';

Future<void> startServerStreaming() async {
  // 1. Get the Terra user ID
  final userId = await TerraFlutterRt.getUserId();
  if (userId == null) return;

  // 2. Get a streaming token from your backend
  final token = await fetchStreamingTokenFromBackend(userId);

  // 3. Start streaming to Terra's server
  await TerraFlutterRt.startRealtimeToServer(
    Connection.ble,
    [DataType.heartRate, DataType.steps],
    token,
  );
}
```

{% hint style="info" %}
**Flutter has separate functions** for local and server streaming:

* `startRealtimeToApp`: streams to a local callback only (no server)
* `startRealtimeToServer`: streams to Terra's websocket server only (no local callback)

To receive data both locally and on your server, call `startRealtimeToApp` for the local callback and have your backend consume from the [Terra websocket](https://docs.tryterra.co/streaming-api/terra-greater-than-your-backend.md).
{% endhint %}

Your backend should generate the streaming token by calling:

{% openapi src="<https://raw.githubusercontent.com/tryterra/openapi/refs/heads/master/dist/core/rt-bundled.yaml>" path="/auth/user" method="post" %}
<https://raw.githubusercontent.com/tryterra/openapi/refs/heads/master/dist/core/rt-bundled.yaml>
{% endopenapi %}
