Connect your Flutter app
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.
Before you start
Section titled “Before you start”- Your shop’s Access Token from Settings › Shop & Integration › General: Find your Access Token and Secret Key. 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.
- 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. 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
Section titled “Install”dependencies: releva_sdk: ^0.3.2Run flutter pub get. For push, add Firebase and generate firebase_options.dart:
flutter pub add firebase_core firebase_messagingflutterfire configureNo 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
Section titled “Configure”1. Client, device id, profile id
Section titled “1. Client, device id, profile id”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:
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
Section titled “2. Register the push token”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
Section titled “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.
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
Section titled “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:
-
Open
ios/Runner.xcworkspacein Xcode and select File › New › Target. Choose Notification Service Extension and name itRelevaNotificationService. -
Add the extension target to
ios/Podfile, then runpod installinios:target 'RelevaNotificationService' douse_frameworks!pod 'Firebase/Messaging'end -
Replace the generated
NotificationService.swiftwith the package’s template,ios/Templates/NotificationService.swift. Find it in your pub cache underhosted/pub.dev/releva_sdk-<version>/. -
In the extension’s
Info.plist, setNSExtensionPrincipalClasstoRelevaNotificationService.
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
Section titled “4. Track screens with page tokens”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:
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:
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
Section titled “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:
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
Section titled “Upgrade from 0.2.x or earlier”- Raise your project to the requirements in Before you start: Flutter 3.27, iOS 15.0, Android
minSdk23,firebase_messaging^16.7.0withfirebase_core^4.14.0, and the matching versions of your other FlutterFire plugins. - Change the dependency to
releva_sdk: ^0.3.2and runflutter pub get. - If you use the Notification Service Extension, copy
ios/Templates/NotificationService.swiftinto it again. - 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
Section titled “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.
Troubleshooting
Section titled “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.
A huawei or other token never receives a push. Only android and ios tokens are targeted.
What syncs
Section titled “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 |