# Session Replay Flutter Standalone SDK

This article covers the installation of Session Replay for Flutter.

{% callout type="warning" heading="iOS and Android only" %}
The Session Replay Flutter SDK supports iOS and Android only. The SDK doesn't support Flutter Web, macOS, Windows, or Linux.
{% /callout %}

{% callout type="warning" heading="Early Access" %}
Session Replay for Flutter is in Early Access. APIs may change and you should expect significant changes before the feature reaches General Availability.

If you're upgrading from an earlier beta, refer to [Upgrade from earlier beta versions](#upgrade-from-earlier-beta-versions) for breaking API changes.

To report issues with Session Replay for Flutter, contact [Amplitude support](https://gethelp.amplitude.com/hc/en-us/requests/new).
{% /callout %}

## Before you begin

Use the latest version of the [`amplitude_session_replay`](https://pub.dev/packages/amplitude_session_replay) package.

The Session Replay Flutter SDK requires that:

1. Your application runs on iOS 13.0+ or Android 5.0+ (minSdk 21).
2. Your project uses Dart SDK 3.7.2 or later and Flutter SDK 3.29.2 or later.
3. You can provide a `device ID` and `session ID` to the SDK. These values must match the identifiers you send as event properties to Amplitude.

The SDK doesn't provide session management. Your application or a third-party integration must update the SDK when the session ID or device ID changes.

### Compatibility

| Requirement | Minimum version |
| --- | --- |
| Dart SDK | 3.7.2 |
| Flutter SDK | 3.29.2 |
| iOS | 13.0 |
| Android minSdk | 21 (Android 5.0) |
| Android compileSdk | 36 |

## Quickstart

Add Session Replay to your `pubspec.yaml`:

```yaml
dependencies:
  amplitude_session_replay: ^0.1.0-beta.5
```

Then run `flutter pub get`.

`SessionReplay` is a process-wide singleton. Access it through `SessionReplay.instance`, and don't construct it directly.

Configure your application code:

1. Call `SessionReplay.instance.init()` with a `SessionReplayConfig`, passing your API key, device ID, and session ID. `init()` is synchronous. It stores the config and installs the message channel handler.
2. Call `start()` to initialize the native SDK and begin recording.
3. When the session ID or device ID changes, call `setSessionId()` or `setDeviceId()` to keep Session Replay synchronized.

```dart
import 'package:amplitude_session_replay/amplitude_session_replay.dart';
import 'package:flutter/widgets.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  // init() is synchronous: it stores the config and installs the channel handler.
  SessionReplay.instance.init(
    SessionReplayConfig(
      apiKey: 'YOUR_AMPLITUDE_API_KEY',
      deviceId: 'your-device-id',
      sessionId: DateTime.now().millisecondsSinceEpoch,
      sampleRate: 0.1,
    ),
  );

  // start() initializes the native SDK and begins recording.
  await SessionReplay.instance.start();

  runApp(const MyApp());
}
```


## Configuration

Pass the following options through `SessionReplayConfig` when you call `SessionReplay.instance.init()`:

| Name | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `apiKey` | `String` | Yes | — | Your Amplitude API key for authentication and data routing. |
| `deviceId` | `String` | Yes | — | Device identifier. Must match the device ID you send with Amplitude events. Must be at least 6 characters. |
| `sessionId` | `int` | No | `-1` | Session identifier in milliseconds since epoch. A value of `-1` means no active session, and Session Replay doesn't record. Must match the session ID you send with Amplitude events. |
| `sampleRate` | `double` | No | `0.0` | Fraction of sessions to capture for replay (0.0–1.0). For example, `0.4` captures 40% of sessions. |
| `logLevel` | `LogLevel` | No | `LogLevel.warn` | Logging verbosity. Options: `LogLevel.off`, `LogLevel.error`, `LogLevel.warn`, `LogLevel.log`, `LogLevel.debug`. |
| `privacyConfig` | `PrivacyConfig` | No | `PrivacyConfig.medium` | Automatic masking behavior. Options: `PrivacyConfig.conservative`, `PrivacyConfig.medium`, `PrivacyConfig.light`. |
| `enableRemoteConfig` | `bool` | No | `true` | Enables [remote configuration](#remote-configuration) from Amplitude servers. |
| `optOut` | `bool` | No | `false` | When `true`, Session Replay doesn't record or upload data. Use `setOptOut()` to change at runtime. |
| `serverZone` | `ServerZone` | No | `ServerZone.us` | Server zone for data residency. Set to `ServerZone.eu` for EU data center. |

### Remote configuration

Enable remote configuration to set Sample Rate and Masking Level in Amplitude. 

{% callout type="note" heading="Remote configuration and testing" %}
With `enableRemoteConfig` set to `true`, settings you define in Amplitude take precedence over settings you define locally in the SDK. For this reason, while testing your application, you should **disable** remote configuration to ensure you can set `sampleRate` to `1`, and ensure you capture test sessions.

{% /callout %}

### Mask onscreen data

Session Replay provides three Flutter widgets for privacy control. These widgets apply to the entire subtree of the wrapped widget. Priority order: `AmpBlock` > `AmpMask` > `AmpUnmask`.

#### Privacy levels

The `privacyConfig` option controls automatic masking behavior:

| Level | Behavior |
| --- | --- |
| `PrivacyConfig.conservative` | Masks all text and all form fields. |
| `PrivacyConfig.medium` (default) | Masks all form fields and text inputs. |
| `PrivacyConfig.light` | Masks only password fields. |

#### AmpMask

Replaces every character of captured text with an asterisk (`*`), preserving the original text length and layout. Use this to protect sensitive information that the automatic privacy level doesn't catch:

```dart
AmpMask(
  child: Text('Sensitive information'),
)
```

#### AmpBlock

Blocks an entire subtree from recording and replaces it with a placeholder. Use this for highly sensitive content:

```dart
AmpBlock(
  child: TextField(
    decoration: InputDecoration(labelText: 'Password'),
  ),
)
```

#### AmpUnmask

Prevents automatic masking from privacy level rules. Use this to reveal content that the privacy level would otherwise mask. `AmpUnmask` can't override a manual `AmpMask` or `AmpBlock`:

```dart
AmpUnmask(
  child: Text('Public content'),
)
```

### User opt-out

To opt users out of session replay collection, pass `optOut: true` during initialization, or call `setOptOut(optOut: true)` at runtime. Opted-out users don't record or upload replay data.

```dart
await SessionReplay.instance.setOptOut(optOut: true);
```

### EU data residency

Amplitude customers who use the EU data center can access Session Replay. Set `serverZone` to `ServerZone.eu` during initialization.

```dart
SessionReplay.instance.init(
  SessionReplayConfig(
    apiKey: 'YOUR_AMPLITUDE_API_KEY',
    deviceId: 'your-device-id',
    sessionId: DateTime.now().millisecondsSinceEpoch,
    serverZone: ServerZone.eu,
  ),
);
```

### Sampling rate

By default, Session Replay captures 0% of sessions for replay. Use the `sampleRate` configuration option to set the percentage of total sessions that Session Replay captures. For example:

To set the `sampleRate` consider the monthly quota on your Session Replay plan. For example, if your monthly quota is 2,500,000 sessions, and you average 3,000,000 monthly sessions, your quota is 83% of your average sessions. In this case, to ensure sampling lasts through the month, set `sampleRate` to `.83` or lower.

Keep the following in mind as you consider your sample rate:

- When you reach your monthly session quota, Amplitude stops capturing sessions for replay.
- Session quotas reset on the first of every month.
- Use sample rate to distribute your session quota over the course of a month, rather than using your full quota at the beginning of the month.
- To find the best sample rate, Amplitude recommends that you start low, for example `.01`. If this value doesn't capture enough replays, raise the rate over the course of a few days. For ways to monitor the number of session replays captured, see [View the number of captured sessions](https://amplitude.com/docs/session-replay#view-the-number-of-captured-sessions).
- Replays with [processing errors](https://amplitude.com/docs/session-replay/session-replay-plugin#troubleshooting) don't count toward your monthly quota. Replays with a retention error message have already been counted against the quota, when the session was still in the retention period.

```dart
SessionReplay.instance.init(
  SessionReplayConfig(
    apiKey: 'YOUR_AMPLITUDE_API_KEY',
    deviceId: 'your-device-id',
    sessionId: DateTime.now().millisecondsSinceEpoch,
    sampleRate: 0.01, // Capture 1% of sessions
  ),
);
```

### Update the session ID

When your session ID changes (for example, on user login or session timeout), update Session Replay:

```dart
final newSessionId = DateTime.now().millisecondsSinceEpoch;
await SessionReplay.instance.setSessionId(newSessionId);
```

### Start and stop recording

Control recording for specific pages or features:

```dart
// Stop recording before entering a restricted area
await SessionReplay.instance.stop();

// Resume recording after leaving the restricted area
await SessionReplay.instance.start();
```

### Disable replay collection

After you enable Session Replay, it runs on your app until either:

- The user leaves your app.
- You call `SessionReplay.instance.stop()`.
- You call `SessionReplay.instance.dispose()`.

Call `SessionReplay.instance.stop()` before a user navigates to a restricted area of your app to disable replay collection while the user is in that area.

Call `SessionReplay.instance.start()` to re-enable replay collection when the user returns to an unrestricted area of your app.

### Hybrid and add-to-app

If your Flutter module runs inside a native iOS or Android host that already integrates the Amplitude Session Replay native SDK, call `SessionReplay.instance.attach()` instead of `init()`. This installs the message channel handler and lets the host app's native SDK own the API key, device ID, session ID, sampling, masking, and upload lifecycle. Don't pass a `SessionReplayConfig`. The native SDK owns configuration in this mode.

```dart
import 'package:amplitude_session_replay/amplitude_session_replay.dart';
import 'package:flutter/widgets.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();

  // The native SDK owns config and lifecycle. attach() only installs the
  // channel handler so native start commands reach the Flutter engine.
  SessionReplay.instance.attach();

  runApp(const MyApp());
}
```

In hybrid mode, the native SDK owns the recording lifecycle. `start()`, `stop()`, `flush()`, `setOptOut()`, `setSessionId()`, and `setDeviceId()` log a warning and no-op. Configure those on the native SDK instead. `dispose()` tears down only the Dart channel handler and engine, and leaves the native SDK alone.

If your app runs multiple Flutter engines (for example, `FlutterEngineGroup` with several Dart entry points), call `attach()` in each entry point. Each engine runs its own isolate with its own `SessionReplay.instance`.

## Methods

Call these methods on the `SessionReplay.instance` singleton:

| Method | Returns | Description |
| --- | --- | --- |
| `init(SessionReplayConfig)` | `void` | Register the config and install the channel handler (Flutter-only mode). Synchronous and one-shot per lifecycle. Call `dispose()` before re-initializing with a new config. |
| `attach()` | `void` | Install the channel handler in hybrid mode, where the native SDK owns configuration and lifecycle. Use instead of `init()`. |
| `start()` | `Future<void>` | Start recording. Initializes the native SDK on first call. |
| `stop()` | `Future<void>` | Stop recording. Call `start()` to resume. |
| `dispose()` | `Future<void>` | Release all resources and return the singleton to its uninitialized state. Call `init()` or `attach()` again to reuse it. |
| `flush()` | `Future<void>` | Force-upload any pending replay data. Useful before the app backgrounds or terminates. |
| `setSessionId(int)` | `Future<void>` | Update the session ID. |
| `sessionId()` | `Future<int>` | Get the current session ID. |
| `setDeviceId(String)` | `Future<void>` | Update the device ID. |
| `deviceId()` | `Future<String>` | Get the current device ID. |
| `setOptOut(optOut: bool)` | `Future<void>` | Toggle opt-out at runtime. When `true`, stops recording and data upload. |
| `optOut` (getter) | `bool` | Get the current opt-out status. |

### Lifecycle

![Session Replay SDK lifecycle: init(config) creates the Initialized state, start() moves to Started, stop() moves to Stopped, start() returns Stopped to Initialized, dispose() from any state moves to Disposed, and init(config) revives Disposed back to Initialized.](https://amplitude.com/docs/images/diagrams/flutter-session-replay-lifecycle.svg){.diagram-light}
![Session Replay SDK lifecycle: init(config) creates the Initialized state, start() moves to Started, stop() moves to Stopped, start() returns Stopped to Initialized, dispose() from any state moves to Disposed, and init(config) revives Disposed back to Initialized.](https://amplitude.com/docs/images/diagrams/flutter-session-replay-lifecycle.dark.svg){.diagram-dark}

`init()` is one-shot per lifecycle: it's only callable from the uninitialized (or disposed) state. To re-initialize with a new config, call `dispose()` first, then `init()` again.

You can call `dispose()` from any state. It returns the singleton to its uninitialized state, so a later `init()` or `attach()` cleanly revives it. Use `dispose()` for permanent teardown only. To temporarily pause and resume recording, use `stop()` and `start()` instead.

## Upgrade from earlier beta versions

Version `0.1.0-beta.5` simplifies installation and reworks the `SessionReplay` API. `SessionReplay` is now a process-wide singleton, and the `SessionReplayWidget` wrapper is no longer required.

### Breaking changes

For Flutter-only apps:

| Old API | New API |
| --- | --- |
| `SessionReplay(config)` constructor | `SessionReplay.instance.init(config)` |
| `SessionReplayWidget(sessionReplay: ..., app: ...)` | Removed. No widget wrapping needed |
| `sessionReplayProperties()` | Removed. Replays match by `deviceId` and `sessionId` |

For hybrid and add-to-app:

| Old API | New API |
| --- | --- |
| `SessionReplayConfig.shouldInitializeNativeSDK: false` | Removed. Call `SessionReplay.instance.attach()` |
| `ensureInitialized()` | `SessionReplay.instance.attach()` |

### Flutter-only apps

Replace the constructor and `SessionReplayWidget` wrapper with `SessionReplay.instance.init()` and `start()`:

```dart
// Before
final sessionReplay = SessionReplay(
  SessionReplayConfig(apiKey: '...', sampleRate: 1.0),
);
runApp(SessionReplayWidget(sessionReplay: sessionReplay, app: const MyApp()));
await sessionReplay.start();

// After
SessionReplay.instance.init(          // synchronous, no await
  SessionReplayConfig(apiKey: '...', sampleRate: 1.0),
);
await SessionReplay.instance.start();
runApp(const MyApp());                // no SessionReplayWidget wrapping needed
```

- `init()` is one-shot per lifecycle. Call `await SessionReplay.instance.dispose()` before re-initializing with a new config.
- Setters (`setSessionId()`, `setDeviceId()`, `setOptOut()`) still work between `init()` and `start()`.

### Hybrid and add-to-app

Replace the placeholder config and widget wrapper with a single `attach()` call:

```dart
// Before — placeholder config + widget wrapper
return SessionReplayWidget(
  sessionReplay: SessionReplay(
    const SessionReplayConfig(
      apiKey: 'YOUR_API_KEY',
      deviceId: 'YOUR_DEVICE_ID',
      shouldInitializeNativeSDK: false,
    ),
  ),
  app: MaterialApp(...),
);

// After — one line per entry point, no config needed
void main() {
  WidgetsFlutterBinding.ensureInitialized();
  SessionReplay.instance.attach(); // native owns config and lifecycle
  runApp(const MyApp());
}
```

- Call `attach()` in every Dart entry point. Each Flutter engine is its own isolate with its own `SessionReplay.instance`.
- Remove any host-app native SDK version pin (for example, a Gradle `resolutionStrategy.force(...)`) and let it resolve within the range the Flutter plugin declares.

### Session Replay properties

Remove all calls to `sessionReplayProperties()`. Amplitude matches replays to analytics events by `deviceId` and `sessionId`. Make sure those match the identifiers you send with your analytics events. For more information, refer to [Session matching](https://amplitude.com/docs/session-replay/session-matching).

The `AmpMask`, `AmpUnmask`, and `AmpBlock` privacy widgets are unchanged.

## Data retention, deletion, and privacy

Session replay uses existing Amplitude tools and APIs to handle privacy and deletion requests.
<!--vale off-->
{% callout type="note" heading="Consent management and Session Replay" %}
While privacy laws and regulations vary across states and countries, certain constants exist, including the requirements to disclose in a privacy notice the categories of personal information you are collecting, the purposes for its use, and the categories of third parties with which personal information is shared. When implementing a session replay tool, you should review your privacy notice to make sure your disclosures remain accurate and complete. And as a best practice, review your notice with legal counsel to make sure it complies with the constantly evolving privacy laws and requirements applicable to your business and personal information data practices.
{% /callout %}


### Retention period

If your Amplitude plan includes Session Replay, Amplitude retains raw replay data for 30 days from the date of ingestion. 

If you purchase extra session volume, Amplitude retains raw replay data for 90 days from the date of ingestion. If you need a more strict policy, contact Amplitude support to set the value to 30 days.

Changes to the retention period impact replays ingested after the change. Sessions captured and ingested before a retention period change retain the previous retention period.

Retention periods are set at the organization level. Replays that are outside of the retention period aren't viewable in Amplitude.

### DSAR API

The Amplitude [DSAR API](https://amplitude.com/docs/apis/analytics/ccpa-dsar) returns metadata about session replays, but not the raw replay data. All events that are part of a session replay include a `[Amplitude] Session Replay ID` event property. This event provides information about the sessions collected for replay for the user, and includes all metadata collected with each event.

```json
{
  "amplitude_id": 123456789,
  "app": 12345,
  "event_time": "2020-02-15 01:00:00.123456",
  "event_type": "first_event",
  "server_upload_time": "2020-02-18 01:00:00.234567",
  "device_id": "your device id",
  "user_properties": { ... }
  "event_properties": {
    "[Amplitude] Session Replay ID": "cb6ade06-cbdf-4e0c-8156-32c2863379d6/1699922971244"
  }
  "session_id": 1699922971244,
}
```

### Data deletion

Session Replay uses Amplitude's [User Privacy API](https://amplitude.com/docs/apis/analytics/user-privacy) to handle deletion requests. Successful deletion requests remove all session replays for the specified user.

When you delete the Amplitude project on which you use Session Replay, Amplitude deletes that replay data.

### Bot filter

Session Replay uses the same [block filter](https://amplitude.com/docs/data/block-bot-traffic) available in the Amplitude app. Session Replay doesn't block traffic based on event or user properties.

## Known limitations

1. **Beta status**: APIs may change. Expect breaking changes before the stable release.
2. **RSuperellipse capture**: Requires Flutter 3.32 or later. Base functionality works on Flutter 3.29.2+.
3. **Multi-view apps**: In Flutter-only mode, the SDK captures the app's primary render view. For hybrid and add-to-app setups that run multiple Flutter engines, call `attach()` in each Dart entry point (refer to [Hybrid and add-to-app](#hybrid-and-add-to-app)).
4. **Remote config override**: When `enableRemoteConfig` is `true`, server settings can override the local `sampleRate` and privacy settings.
5. **Native SDK dependencies**: iOS uses `AmplitudeSessionReplay` ~>0.12.2. Android uses `session-replay-android` [0.27.0, 0.28.0).

## Troubleshooting

### Session replays don't appear in Amplitude

Session replays may not appear because of:

- Lack of network connectivity.
- Sampling excluded the session (`sampleRate` too low).
- No events sent with matching `deviceId` and `sessionId` for the session.
- A missing `SessionReplay.instance.start()` call after `init()`.

#### Verify your configuration

1. Check that `sampleRate` is greater than `0`. The default is `0.0`, which captures no sessions.
2. Confirm you call `SessionReplay.instance.start()` after `SessionReplay.instance.init()`.
3. Ensure the `apiKey`, `deviceId`, and `sessionId` match the values you send with analytics events.

#### Verify network connectivity

Ensure your app has access to the internet and try again.

#### Check sample rate

The default `sampleRate` is `0.0`. Update the rate to a higher number. For more information, refer to [Sampling rate](#sampling-rate).

### Session Replay processing errors

Replays appear in Amplitude within minutes of ingestion. Delays or errors may result from:

- Mismatched API keys or device IDs between Session Replay and your analytics instrumentation.
- Session Replay references the wrong project.
- Short sessions. If a user bounces within a few seconds of initialization, the SDK may not have time to upload replay data.
