SDKs
Flutter
sapagan_flutter identifies people, tracks events, registers push tokens and shows in-app messages.
sapagan_flutter is the Flutter client for Sapagan. It identifies the user, tracks events and screens, registers push tokens, reports push opens and shows in-app messages, with an offline queue. It is shaped like Customer.io's customer_io package, so a switch is mostly renames.
Version 0.4.0 needs Dart 3.4 and Flutter 3.22 or newer. It depends on http and shared_preferences, and not on firebase_messaging: your app passes tokens and push data in.
Install#
The package is not on pub.dev yet. Add it as a git dependency from your Sapagan contact's repository, pinned to a tag or commit, never a branch:
dependencies:
sapagan_flutter:
git:
url: <repository url Sapagan gives you>
path: packages/flutter
ref: <tag or commit>Initialise#
Use an app key and an identity token provider.
import 'package:sapagan_flutter/sapagan_flutter.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Sapagan.initialize(SapaganConfig.fromKey(
apiHost: const String.fromEnvironment('SAPAGAN_API_HOST'),
key: const String.fromEnvironment('SAPAGAN_APP_KEY'), // ktg_app_...
userTokenProvider: () async => (await myApi.get('/me/sapagan-token')).data['token'] as String?,
pushMetricsEnabled: true,
));
runApp(const App());
}Useful options: flushInterval (30 s), flushAt (20 queued items), maxBatchSize (100), maxQueueSize (1,000 kept offline, oldest dropped), requestTimeout (15 s), sessionTimeout (30 min), appId and logLevel.
Identify, track and screens#
| Call | What it does |
|---|---|
Sapagan.instance.identify(id, traits: {...}) | Links this device to the person. Traits become profile attributes. |
clearIdentify() | At logout: removes the device token from the person, forgets the user, starts a new anonymous id. |
track(name, properties: {...}) | Records an event. |
screen(name) | Records the event Screen Viewed and sets the current screen for in-app rules. |
setProfileAttributes({...}) | Updates attributes. Ignored before identify. |
registerDeviceToken(token) / deleteDeviceToken() | Attaches or removes the push token. A token registered before identify is held until identify. |
Every call returns a Future you may ignore. Calls apply in order and nothing throws into the app. Before identify, events are recorded against an anonymous id, and the first identify links that id to the profile.
Everything goes through a persisted queue and is sent to POST /v1/batch in batches, with backoff on failure. Each event carries a dedupeId and each request an Idempotency-Key, so a retry never counts twice.
Identity tokens#
The app key is public. A token signed by your backend binds the device to the right person. See Identity tokens for the format and your backend's code.
- The provider is called only when the SDK has no usable token. The token stays in memory and is never stored or logged.
- Return
nullwhen nobody is signed in. - A refused token (
401 invalid_user_token) is asked for once more and the batch retried. - With tokens,
emailandphonetraits stay attributes. Your backend sets them with its server key.
Push#
Pass tokens and push data in from Firebase.
final fcm = FirebaseMessaging.instance;
final token = await fcm.getToken();
if (token != null) Sapagan.instance.registerDeviceToken(token);
Sapagan.instance.listenToTokenRefresh(fcm.onTokenRefresh);
FirebaseMessaging.onMessageOpenedApp.listen((m) => Sapagan.instance.trackPushOpened(m.data));
final initial = await fcm.getInitialMessage();
if (initial != null) Sapagan.instance.trackPushOpened(initial.data);
FirebaseMessaging.onMessage.listen((m) => Sapagan.instance.trackPushDelivered(m.data));trackPushOpened returns a SapaganPush with the delivery id and the deep link for a Sapagan push, and null for any other push. A push without data['k_did'] is never reported.
For delivered reports while the app is in the background, call Sapagan.trackPushDeliveredInBackground(config, m.data) from the FCM background handler.
Android: nothing beyond Firebase's own setup. iOS: pass the FCM registration token, not the raw APNs token, and call requestPermission() first. Sapagan sends to both platforms through FCM. See FCM and APNs credentials.
In-app messages#
In-app messages (banners, modals, full screen and inline slots) are off until you set SapaganConfig.inApp.
await Sapagan.initialize(SapaganConfig.fromKey(
apiHost: '...',
key: '...',
inApp: InAppConfig(
onInAppLink: (link) => appRouter.openDeepLink(link),
denyScreens: const ['Checkout', 'Payment*'],
),
));
MaterialApp(builder: (context, child) => SapaganOverlay(child: child!));
Column(children: [const SapaganSlot('home_top'), ...feed]);- Messages come from
GET /v1/inapp/messagesfor the identified user only, cached on the device, withETagsupport. - Triggers run on the device with no round trip:
app_open,screen(with the name you pass toscreen()) andevent. - Rules: not expired, never again after a click or dismiss, per-session and per-day caps, highest priority wins. One banner, modal or full-screen message shows at a time.
- A tap on the message or a link button records
clickedand callsonInAppLink. Closing recordsdismissed. Metrics go toPOST /v1/inapp/events. - Nothing shows on a denied screen.
denyScreenstakes exact names or a prefix ending in*.
Call screen(name) on each screen change, or screen rules cannot work.
Move from customer_io#
| customer_io | sapagan_flutter |
|---|---|
CustomerIO.initialize(config: ...) | Sapagan.initialize(SapaganConfig(...)) |
CustomerIO.instance.identify(userId: id, traits: t) | Sapagan.instance.identify(id, traits: t) |
CustomerIO.instance.track(name: n, properties: p) | Sapagan.instance.track(n, properties: p) |
CustomerIO.instance.screen(title: n) | Sapagan.instance.screen(n) |
CustomerIO.instance.registerDeviceToken(deviceToken: t) | Sapagan.instance.registerDeviceToken(t) |
CustomerIO.pushMessaging.trackMetric(...) | trackPushOpened(data) / trackPushDelivered(data) |
Upgrading#
Version 0.3.0 renamed the package from kentongan_flutter. Stored data moves over by itself. 0.3.x sends no identity token and keeps working only where the workspace does not require identity. See the changelog.