# Connect your Flutter app

> Add the releva_sdk package, set up Firebase with flutterfire, initialise the client with your Access Token, register the push token, handle taps, track screens with page tokens and check in Releva that data arrives.

The Releva Flutter SDK (`releva_sdk`) connects a Flutter app on Android and iOS to Releva: screen and product tracking, product blocks, banners, stories, NPS surveys, app push through Firebase Cloud Messaging and the App Inbox.

> **Note**
>
> The steps on this page describe version 0.3.x of the Flutter SDK. The latest release is 0.3.2 (23 October 2026).

## Before you start

* Your shop’s **Access Token** from **Settings › Shop & Integration › General**: [Find your Access Token and Secret Key](https://releva.ai/documentation/guides/shop-settings/find-your-api-keys/). Never put the **Secret Key** in the app.
* One page token per screen you want to track or personalise, from the **Token:** bar on **Personalization › Product Blocks**: [Pages and tokens](https://releva.ai/documentation/learn/product-blocks/how-product-blocks-work/#pages-and-tokens).
* For push: one Firebase project for both platforms, and its service account uploaded in Releva with **App Type** **Unified**: [Add your Firebase credentials for app push](https://releva.ai/documentation/integrations/mobile/add-firebase-credentials-for-app-push/). The Flutter SDK registers FCM tokens, so **iOS APNs environment** does not apply to it.
* Your app meets the SDK’s requirements:

|                                        | Minimum                                                                                     |
| -------------------------------------- | ------------------------------------------------------------------------------------------- |
| Flutter                                | 3.27 (Dart 3.6)                                                                             |
| iOS deployment target                  | 15.0. Set `platform :ios, '15.0'` in `ios/Podfile` if it is lower.                          |
| Android `minSdk`                       | 23. Set it in `android/app/build.gradle(.kts)` if it is lower.                              |
| `firebase_core` / `firebase_messaging` | `^4.14.0` / `^16.7.0`. `firebase_core` 5 and `firebase_messaging` 17 are not supported yet. |
| `flutter_local_notifications`          | 18.x or 19.x, if your app depends on it directly                                            |

Any other FlutterFire plugins you use must be on the major versions built on `firebase_core` 4, for example `firebase_auth` 6, `cloud_firestore` 6 and `firebase_storage` 13.

If your iOS app uses the UIScene lifecycle (its `Info.plist` has a `UIApplicationSceneManifest`), push taps reach the SDK only with `firebase_messaging` 16.7 or later. With an older version the app opens on its home screen, `onNotificationTapped` is never called and no click is tracked. Keep setting `UNUserNotificationCenter.current().delegate` in `application(_:didFinishLaunchingWithOptions:)` and registering plugins in `didInitializeImplicitFlutterEngine(_:)`, as `flutter_local_notifications` documents for UIScene apps.

## Install

**pubspec.yaml**

```plaintext
dependencies:
  releva_sdk: ^0.3.2
```

Run `flutter pub get`. For push, add Firebase and generate `firebase_options.dart`:

```plaintext
flutter pub add firebase_core firebase_messaging
flutterfire configure
```

No Android manifest changes and no iOS `AppDelegate` changes are needed: Releva sends data-only FCM messages that the SDK displays itself, and the SDK registers its iOS notification categories on start-up. If you added the `RELEVA_NOTIFICATION_CLICK` intent filter from an older guide, remove it.

## Configure

### 1. Client, device id, profile id

```plaintext
import 'package:releva_sdk/client.dart';
import 'package:releva_sdk/services/navigation_service.dart';
import 'package:releva_sdk/types/notification_action.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'firebase_options.dart';


void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
  runApp(MyApp());
}


class _MyAppState extends State<MyApp> {
  late RelevaClient client;


  @override
  void initState() {
    super.initState();
    // realm: '' unless Releva gives you one. accessToken: Settings › Shop & Integration › General.
    client = RelevaClient('', '<yourAccessToken>');
    _initializeSDK();
  }


  Future<void> _initializeSDK() async {
    await client.setDeviceId('<deviceId>');
    await client.setProfileId('<profileId>');   // after login; before that, your own anonymous id
    await client.enablePushEngagementTracking(
      onNotificationTapped: (RelevaNotificationAction action) async {
        // see step 3
      },
    );
    await _registerPushToken();
  }


  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      navigatorObservers: [client.createScreenTrackingService()],   // automatic screen tracking
      navigatorKey: NavigationService.instance.navigatorKey,        // lets onNotificationTapped get a BuildContext
      home: HomeScreen(client: client),
    );
  }
}
```

On **login** `setProfileId(userId)` merges the anonymous history into the account. On **logout** set a fresh anonymous id with `true` as the second argument, so the next visitor’s activity is not merged into the account. `setProfileId` re-registers the stored push token under the new id; registering the token from Firebase again is a safety net:

```plaintext
await client.setProfileId(const Uuid().v4(), true);
final token = await FirebaseMessaging.instance.getToken();
if (token != null) {
  await client.registerPushToken(Platform.isIOS ? DeviceType.ios : DeviceType.android, token);
}
```

### 2. Register the push token

```plaintext
Future<void> _registerPushToken() async {
  final messaging = FirebaseMessaging.instance;
  final settings = await messaging.requestPermission(alert: true, badge: true, sound: true);
  if (settings.authorizationStatus == AuthorizationStatus.authorized) {
    final token = await messaging.getToken();
    if (token != null) {
      await client.registerPushToken(Platform.isIOS ? DeviceType.ios : DeviceType.android, token);
    }
  }
}
```

`DeviceType` accepts `android`, `ios`, `huawei` and `other`; only `android` and `ios` tokens receive pushes from Releva. After this first registration, and once `enablePushEngagementTracking` has run, the SDK re-uploads the token on every launch, every foreground resume and every rotation by Firebase.

### 3. Taps and navigation

Pick one of two ways. **Option 1**, recommended: let the SDK own `onMessage`, `onMessageOpenedApp` and `getInitialMessage`. Only do this if nothing else in your app or its libraries listens to them.

```plaintext
await client.enablePushEngagementTracking(
  onNotificationTapped: (RelevaNotificationAction action) async {
    // action.target: 'screen', 'url', 'inbox' or null (main screen)
    // action.screen: the Screen name set under Mobile Targeting in the Releva push form
    // action.parameters: the KV Pairs
    final context = NavigationService.instance.navigatorKey.currentContext;
    if (context == null) return;
    if (action.target == 'inbox') {
      Navigator.of(context).pushNamedAndRemoveUntil('/inbox', (route) => route.isFirst, arguments: action.parameters);
    } else if (action.target == 'screen' && action.screen != null) {
      Navigator.of(context).pushNamedAndRemoveUntil(action.screen!, (route) => route.isFirst, arguments: action.parameters);
    } else if (action.target == 'url' && action.url != null) {
      final uri = Uri.tryParse(action.url!);
      if (uri != null) await launchUrl(uri, mode: LaunchMode.externalApplication);
    }
  },
);
```

**Option 2**: keep your own Firebase hooks and call `await client.trackEngagement(message)` inside each of `onMessage.listen`, `onMessageOpenedApp.listen` and `getInitialMessage().then`. `client.isRelevaMessage(message)` tells Releva pushes from your own.

### Optional: button text and images on iOS

Without a Notification Service Extension, iOS pushes show an “Open” button when the app is in the background or closed, and no button in the foreground. To show the button text and image from the push, add the extension:

1. Open `ios/Runner.xcworkspace` in Xcode and select **File › New › Target**. Choose **Notification Service Extension** and name it `RelevaNotificationService`.

2. Add the extension target to `ios/Podfile`, then run `pod install` in `ios`:

   ```plaintext
   target 'RelevaNotificationService' do
     use_frameworks!
     pod 'Firebase/Messaging'
   end
   ```

3. Replace the generated `NotificationService.swift` with the package’s template, `ios/Templates/NotificationService.swift`. Find it in your pub cache under `hosted/pub.dev/releva_sdk-<version>/`.

4. In the extension’s `Info.plist`, set `NSExtensionPrincipalClass` to `RelevaNotificationService`.

Releva sends iOS pushes with `mutable-content: 1`, so the extension runs for every Releva push. After each SDK update, copy the template into the extension again.

### 4. Track screens with page tokens

```plaintext
final response = await client.trackProductView(
  screenToken: '<productPageToken>',
  productId: 'DEMO-1001',
  categories: ['Shoes'],
);
await client.trackScreenView(screenToken: '<homePageToken>', productIds: ['DEMO-1001', 'DEMO-1002']);
await client.trackSearchView(screenToken: '<searchPageToken>', query: 'red running shoes', resultProductIds: ['DEMO-1001']);
await client.trackCheckoutSuccess(screenToken: '<checkoutPageToken>', orderedCart: Cart.active([...]));


if (response.hasRecommenders) {
  for (final recommender in response.recommenders) {
    print('${recommender.name}: ${recommender.response.length} products');
  }
}
```

`screenToken` must be a page token copied from **Personalization › Product Blocks**. Names such as `'home_screen'` or `'product_detail'` are not tokens: a screen sent with one records no page view and returns no banners or stories, while Releva still answers `200`.

Cart and wishlist are stateful; set an active cart with an empty list when the shopper empties it:

```plaintext
CartProduct product = CartProduct('DEMO-1001', 29.99, 1, CustomFields([CustomField('size', ['M'])], [], []));
await client.setCart(Cart.active([product]));
await client.setWishlist([WishlistProduct('DEMO-1002', CustomFields.empty())]);
```

Anything else goes through `PushRequest()` with `.locale`, `.currency`, `.pageFilter(NestedFilter.and([...]))`, `.screenView('<pageToken>')`, `.productView(...)`, `.customEvents([...])` and `client.push(request)`.

Filters combine with nested AND and OR groups on listing and search screens:

```plaintext
final filter = NestedFilter.and([
  SimpleFilter.priceRange(minPrice: 10, maxPrice: 100),
  NestedFilter.or([
    SimpleFilter.brand(brand: 'Nike'),
    SimpleFilter.brand(brand: 'Adidas'),
  ]),
  SimpleFilter.color(color: 'red'),
]);
await client.trackSearchView(screenToken: '<searchPageToken>', query: 'shoes', filter: filter);
```

### 5. On-screen content

Banners (`BannerDisplayWidget` around a screen), stories, NPS (`NpsOverlayWidget`) and the App Inbox (`client.initializeInbox()` after the profile id, then `client.inbox`) are each optional. Every feature is on by default. Turn off what you do not use with `RelevaConfig`:

```plaintext
RelevaClient('', '<yourAccessToken>', config: RelevaConfig(
  enableTracking: true,
  enableScreenTracking: true,       // the NavigatorObserver
  enablePushNotifications: true,
  enableInbox: true,
  enableRequestLogging: true,       // one debugPrint line per HTTP request, without the body
  requestTimeout: Duration(seconds: 30),
  maxRetryAttempts: 3,              // retries after a network error or a 5xx
));
```

## Upgrade from 0.2.x or earlier

1. Raise your project to the requirements in [Before you start](https://releva.ai/documentation/integrations/flutter/connect-your-flutter-app/#before-you-start): Flutter 3.27, iOS 15.0, Android `minSdk` 23, `firebase_messaging` `^16.7.0` with `firebase_core` `^4.14.0`, and the matching versions of your other FlutterFire plugins.
2. Change the dependency to `releva_sdk: ^0.3.2` and run `flutter pub get`.
3. If you use the Notification Service Extension, copy `ios/Templates/NotificationService.swift` into it again.
4. Check your existing banners on a device. Popups without a set size now show as a centred card sized to their content (600 wide by default) instead of filling the screen, and banners use the card and close-button styling set in the banner editor.

On the first launch after the update, the SDK re-uploads the stored push token once under the current profile.

## Verify

Run the app, accept the notification permission and open a screen with a page token. Then follow [Check that your mobile app is connected](https://releva.ai/documentation/integrations/mobile/check-that-your-mobile-app-is-connected/).

## Troubleshooting

**No Push Notification Subscribe event.** The permission was not granted, or `_registerPushToken` did not run.

**Taps are not tracked.** Your app or a library already listens to `onMessageOpenedApp` or `getInitialMessage`, so the SDK’s hooks (option 1) never fire. Use option 2.

**No banners, stories or product blocks, and no Viewed Page event.** The `screenToken` is not a page token. Copy it from **Personalization › Product Blocks**.

**`400` from the push endpoint.** Messages are listed in the [push notifications reference](https://releva.ai/documentation/reference/push-notifications/overview/#register-a-mobile-app-push-token).

**A `huawei` or `other` token never receives a push.** Only `android` and `ios` tokens are targeted.

## What syncs

Endpoints and identifiers are the same as for the other SDKs.

| Data                                                                        | Endpoint                                                                                       | When                                                                                                                                  |
| --------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
| Screen, product, search views; custom events; cart, wishlist; checkout      | `POST /api/v0/push`                                                                            | `track*` methods, `push(request)`, the `NavigatorObserver`; `setCart`/`setWishlist` changes                                           |
| App push token                                                              | `POST /api/v0/appPush/tokens`                                                                  | `registerPushToken`, then automatically on launch, resume and rotation. Writes a **Push Notification Subscribe** event each time      |
| Push tap                                                                    | `GET <callbackUrl>` from the push data                                                         | `enablePushEngagementTracking` or `trackEngagement`                                                                                   |
| Banner impressions and actions, story actions                               | `POST /api/v0/impressions`, `POST /api/v0/push/events`                                         | Widgets                                                                                                                               |
| NPS answer                                                                  | `POST /api/v0/nps/{token}/submissions`                                                         | `NpsOverlayWidget`                                                                                                                    |
| App Inbox                                                                   | `GET /api/v0/inbox/messages`, `GET /api/v0/inbox/unread-count`, read, read-all, delete, action | `client.inbox`                                                                                                                        |
| Products, orders paid outside the app, refunds, profile attributes, consent | not sent by the SDK                                                                            | Your backend: [What your backend still sends](https://releva.ai/documentation/integrations/mobile/mobile-sdks-overview/#what-your-backend-still-sends) |

## Next steps

* [Add your Firebase credentials for app push](https://releva.ai/documentation/integrations/mobile/add-firebase-credentials-for-app-push/): Upload the Firebase service account Releva sends your app push through.
* [Check that your mobile app is connected](https://releva.ai/documentation/integrations/mobile/check-that-your-mobile-app-is-connected/): Confirm that push token registrations arrive and the shopper’s profile shows app push.
* [Mobile SDKs overview](https://releva.ai/documentation/integrations/mobile/mobile-sdks-overview/): See what every SDK sends to Releva and what still has to come from your backend.
* [How the App Inbox works](https://releva.ai/documentation/learn/inbox/how-the-app-inbox-works/): Learn how inbox messages reach your app and how it keeps its inbox in sync.