jatayu_flutter 0.10.0
jatayu_flutter: ^0.10.0 copied to clipboard
Mobile analytics, attribution, observability, and remote configuration for the Jatayu platform.
Jatayu for Flutter #
Mobile analytics, attribution, error tracking, and remote configuration for iOS and Android, backed by the Jatayu platform.
- Analytics — offline-first event queue with batched delivery, sessions, screens, and client-reported revenue.
- Identity — anonymous installs, user IDs, traits, groups, Firebase Auth, and server-minted identity tokens.
- Remote config — typed flags and values per environment, cached offline, refreshed in the background.
- Attribution — Play Install Referrer on Android; SKAdNetwork and AdAttributionKit bridges on iOS; referral codes and campaign links.
- Observability — automatic Dart/Flutter error capture plus timed traces.
- Uninstall signals — APNs / FCM token registration for server-side invalidation checks.
Requires Dart >=3.3.0, Flutter >=3.19.0, iOS 13+ or Android API 21+. Flutter Web and desktop are not supported.
Install #
flutter pub add jatayu_flutter
import 'package:jatayu_flutter/jatayu_flutter.dart';
Quickstart #
- In the Jatayu dashboard, open Applications and create (or select) your app. Copy the public SDK key and note your Jatayu server origin (for example
https://analytics.your-domain.com). - Initialize once, before
runApp, with collection switched off until your app has permission to collect analytics:
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Jatayu.initialize(JatayuOptions(
endpoint: 'https://analytics.your-domain.com',
writeKey: 'YOUR_APP_WRITE_KEY',
appVersion: '1.0.0', // or 'auto' to read the native app version
consent: false,
));
runApp(const MyApp());
}
- After the user accepts (your own consent UI, onboarding step, or settings toggle), enable collection:
await Jatayu.instance.setConsent(true);
await Jatayu.instance.track('product_view', {'product_id': 'pro'});
endpointmust be an HTTPS origin (https://host, no path or query string). Plain HTTP is accepted only for local development hosts (localhost,127.0.0.1,10.0.2.2,::1) together withallowInsecureLocalhost: true.
Consent and privacy #
Collection is opt-in. The SDK sends nothing until consent is granted:
consent: false(the default) at initialize means no identifiers are created, no events are queued, and no network calls are made.setConsent(true)creates the installation ID, records the launch lifecycle events (below), flushes, and fetches remote config.setConsent(false)clears queued events, cached config, and installation identity on-device and stops future collection. A request already accepted by the server cannot be recalled; use the dashboard's erasure operation for server-side data.- Consent here is an application-level collection switch, not Apple ATT authorization. The SDK requests no location permission, and no advertising identifier unless you opt in (see Anti-fraud fingerprinting).
- Device fingerprinting is gated by the same consent flag and reports only salted hashes;
setConsent(false)discards the cached report along with everything else. - On-device storage (SharedPreferences) is app-private but not encrypted. Do not put secrets or sensitive personal data in event properties. Registered push tokens are encrypted server-side.
- Invalid event arguments throw
ArgumentErrorbefore anything is queued. All callbacks run on the main Flutter isolate, and the optionalonDiagnosticcallback receives non-sensitive diagnostic messages only (no payloads or keys).
Tracking events #
final analytics = Jatayu.instance;
await analytics.track('product_view', {'product_id': 'pro'});
await analytics.screen('checkout'); // sends screen_view with {'screen': 'checkout'}
await analytics.revenue(29.99, 'USD'); // sends purchase with revenue + currency
await analytics.flush(); // optional: deliver now instead of waiting for the next batch
Automatic screen tracking #
Attach JatayuNavigatorObserver to the navigator so named-route transitions
call screen() for you — screen_view with screen and, when known,
previous_screen. Dialogs and unnamed routes are skipped. Collection still
respects consent, and the observer is a no-op until Jatayu.initialize
(or until you pass client:).
MaterialApp(
navigatorObservers: [JatayuNavigatorObserver()],
routes: {
'/': (_) => const HomePage(),
'/checkout': (_) => const CheckoutPage(),
},
);
GoRouter(
observers: [JatayuNavigatorObserver()],
routes: [/* named GoRoutes */],
);
For Navigator.push, set RouteSettings(name: ...) on the page route, or
supply nameExtractor / routeFilter to map widget types and ignore shells.
Rules enforced client-side (violations throw before queueing):
- Event names: up to 100 characters, matching
[a-zA-Z_$][a-zA-Z0-9_.$ -]*. - Properties: property names up to 100 characters; total encoded size up to 16 KB.
- Revenue: finite, non-negative amount up to 100,000,000 with an uppercase ISO 4217 currency (
'USD','EUR', …).
pendingEventCount exposes the number of events still queued, and installationId the stable per-install anonymous ID.
Identity #
// Tie the install to your own user record.
await Jatayu.instance.identify('your-internal-user-id',
properties: {'plan': 'pro'},
setOnce: {'signup_source': 'referral'},
);
// Update traits without changing the user ID (sends properties_updated).
await Jatayu.instance.setUserProperties({'plan': 'team'});
await Jatayu.instance.setUserProperties({'first_seen': '2026-01-01'}, once: true);
// Group the user (up to 20 group types; sends group_assigned and refreshes config).
await Jatayu.instance.setGroup('organization', 'acme', properties: {'plan': 'pro'});
await Jatayu.instance.removeGroup('organization'); // sends group_removed
// Clear the local user and start fresh (sends identity_reset).
await Jatayu.instance.resetIdentity();
- User IDs: 1–200 characters, must not start with
anon:. - Group types: start with a letter, up to 50 characters of
[word chars, '.', '-']; keys up to 200 characters. - Switching to a different user ID rotates the anonymous ID and clears traits, groups, and the previous identity token.
Firebase Auth and server-minted identity #
// Host app signs in with Firebase, then hands the ID token over (refresh it on expiry).
await Jatayu.instance.authenticateFirebase(firebaseIdToken);
// Or mint identity server-side and pass it to the client.
// The token comes from POST /api/server/users (server key). Never embed a server secret in an app.
await Jatayu.instance.setIdentityToken(userId: 'user_123', token: serverMintedToken);
Authenticated requests automatically carry the identity token (X-Jatayu-User) for referrals and config personalization.
Firebase and RevenueCat profiles #
Jatayu never imports Firebase or RevenueCat data. Report the ids and the dashboard's user page looks the account up live in each connected provider:
await Jatayu.instance.setRevenueCatAppUserId(await Purchases.appUserID);
await Jatayu.instance.setFirebaseUid(FirebaseAuth.instance.currentUser!.uid); // not needed after authenticateFirebase
Remote config #
Publish values per environment (production / staging) in the dashboard; the SDK caches them per environment, refreshes every fifteen minutes, uses ETags, and falls back to cached values offline. Missing, disabled, or out-of-rollout keys return your typed fallback.
await Jatayu.instance.fetchConfig();
final enabled = Jatayu.instance.getBool('onboarding_v2', fallback: false);
final welcome = Jatayu.instance.getString('welcome_message', fallback: 'Hi!');
final price = Jatayu.instance.getNumber('price', fallback: 9.99);
final card = Jatayu.instance.getJson<Map<String, dynamic>>('home_card');
// React to background refreshes.
Jatayu.instance.onConfigChanged.listen((values) => updateUi(values));
configVersion exposes the currently applied config version.
Errors and performance traces #
Dart/Flutter exceptions are captured automatically (captureFlutterErrors: true, the default) without replacing your existing error handlers. Native process crashes, ANRs, hangs, and native stack symbolication are not captured.
// Manual reporting.
await Jatayu.instance.recordError(error, stackTrace, fatal: false);
// Time an operation; records a trace event with durationMs + success, and still rethrows.
final products = await Jatayu.instance.trace('api.products', loadProducts,
properties: {'source': 'home'});
Referrals and campaign links #
// Authenticated users can create a referral link to share.
final link = await Jatayu.instance.createReferralLink(); // {'code': ..., 'url': ...}
// Redeem a code entered by the user (e.g. from an install referrer or a shared link).
await Jatayu.instance.redeemReferral('ABCD1234');
// Pass inbound app/universal links from your host link handler.
// /r/<code> links stage a referral (redeemed automatically once authenticated);
// /l/<id> links resolve the campaign and record an attributed campaign_open.
final result = await Jatayu.instance.handleLink(incomingUri);
// result['click'] holds the open intent's click metadata (country,
// browser/OS, UTM source, referrer host) when the link carried `_jt_c`.
pendingReferralCodeholds a staged code (Play referrerjatayu_referral_codeor an/r/link) until the user authenticates, at which point it is redeemed automatically.- Android campaign attribution reads the Play Install Referrer after consent and matches the click ID server-side to the same app within the link's click window, once only. The referrer is client-supplied, not an attested anti-fraud signal; sideloaded installs may have no referrer.
- Every link open intent carries its click metadata in the URL (
_jt_cplus passthrough UTM params).handleLinkforwards the click id toPOST /api/v1/links/resolve, stages it for the next events batch, and recordscampaign_openwith both ids — so usage is tracked to the tap even when the app was already installed. The staged click is one-shot: a first open claims the install (link_open_click), later opens only record the event. - Campaign and referral links are served from
https://link.jatayu.click(handleLinkaccepts that host and yourendpointhost; override withJatayuOptions.linkHosts). When the app isn't installed, the link opens a landing page that sends visitors to the right store. In in-app browsers that block store links (Instagram, Facebook, TikTok, …), the page guides visitors into Safari or their default browser first. - To open installed apps directly from these links, set the Apple Team ID and Android signing fingerprints in Jatayu → Applications, then register the domain:
<!-- iOS: Runner.entitlements → com.apple.developer.associated-domains -->
<string>applinks:link.jatayu.click</string>
<!-- Android: AndroidManifest.xml, inside your launcher activity -->
<intent-filter android:autoVerify="true">
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="https" android:host="link.jatayu.click" android:pathPrefix="/l/" />
<data android:scheme="https" android:host="link.jatayu.click" android:pathPrefix="/r/" />
</intent-filter>
Push and in-app messages #
enablePush uses Firebase Cloud Messaging on both platforms: it asks for permission, registers the FCM token, shows Android notifications (image and buttons) while the app is open or in the background, and reports delivered / opened / button taps. The same call loads in-app messages.
Host setup:
- Add
google-services.json(Android) andGoogleService-Info.plist(iOS), and callFirebase.initializeApp()beforeenablePush. - Upload an APNs key to the Firebase project so iOS tokens work. iOS images and delivered receipts need a Notification Service Extension; without it, iOS reports sent → opened only.
Info.plist:UIBackgroundModesincludesremote-notification. Enable Push Notifications.- Android
minSdk23 or higher.
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
FirebaseMessaging.onBackgroundMessage(jatayuPushBackground);
runApp(const MyApp());
}
// After analytics consent:
await Jatayu.instance.enablePush(onOpened: (open) {
// open.url is the deep link; open.action is the button id, if any.
});
registerPushToken is still there if the host app owns messaging itself. Tokens must be 16–4096 characters. Paste the Firebase service account under Integrations (or Uninstalls).
Uninstall tracking #
The dashboard's Uninstalls page lists who removed the app, each row linked to their profile. On by default (uninstallTracking: true); two signals feed it:
- Push probes (both platforms). Installs with a push token get a silent probe once they've been quiet for two hours. If FCM or APNs reports the token unregistered, the uninstall is confirmed. With
jatayuPushBackgroundregistered, the SDK answers each probe, which proves the app is still installed. Probes are never shown. - Background heartbeat (Android). After consent, a WorkManager job checks in every eight hours (the server sets the interval), even when nobody opens the app. After two days with no check-in the install is marked likely uninstalled and probed to confirm. This covers installs that never granted notification permission. The check-in sends only a device-scoped token: no events and no identifiers. It never counts as activity, and it stops (and tells the server so) when consent is revoked.
If a flagged install sends anything later, the uninstall is withdrawn. A new install on the same phone, recognised by its fingerprint anchors or the signed-in user, shows as "came back". Use the jt_app_uninstalled journey trigger for win-back emails.
WorkManager (androidx.work:work-runtime) is added by the plugin. It needs no permissions or manifest changes.
iOS attribution (SKAN / AdAttributionKit) #
// iOS only; call both when ad networks use both Apple frameworks.
await Jatayu.instance.updateConversionValue(12, coarseValue: 'medium');
await Jatayu.instance.updateAdAttributionValue(12);
- Conversion values are 0–63. SKAN updates need iOS 14+ (coarse values 16.1+); AdAttributionKit needs iOS 17.4+ and an Xcode SDK that includes it.
- Set the numeric App Store ID in Jatayu → Applications, and add to your app's
Info.plist:
<key>NSAdvertisingAttributionReportEndpoint</key>
<string>https://your-registrable-domain.com</string>
<key>AttributionCopyEndpoint</key>
<string>https://your-registrable-domain.com</string>
- Apple resolves the registrable domain and ignores subdomains. Your domain must route these HTTPS endpoints to Jatayu (no write keys in these URLs — Apple signatures authenticate the postbacks):
POST /.well-known/skadnetwork/report-attribution/
POST /.well-known/appattribution/report-attribution/
A bare hosting subdomain is not a verified Apple postback setup: connect an owned domain and verify delivery from a real device. For APNs, the host app registers for remote notifications, forwards the device token, and enables Background Modes → Remote notifications. The package ships a privacy manifest — review your app's disclosure for the data you choose to send.
Android notes #
Minimum API 23 when using enablePush (Firebase Messaging); API 21 remains enough for analytics alone. The plugin builds with Java 17, Kotlin, and Gradle. Internet permission is included. enablePush requests notification permission on Android 13+. The Play Install Referrer (v2.2) is read through a native bridge only after collection consent, including its click and install-begin timestamps — the server differences these to detect click injection.
Anti-fraud fingerprinting #
The SDK builds a device identity that survives an uninstall/reinstall cycle and a "Clear storage" wipe, so install fraud, repeat-claimed referrals and device farms stay visible. It is on by default and collected only under consent.
await Jatayu.initialize(JatayuOptions(
writeKey: 'pk_live_...',
consent: true,
fingerprint: JatayuFingerprintOptions(
collectHardwareSignals: true,
collectIntegritySignals: true,
),
));
final report = Jatayu.instance.fingerprint;
if (report != null && report.isCompromised) {
// Gate a reward, not the whole app: heuristics have false positives.
}
How the identity persists #
Identity is a set of independent anchors, not one value. Every source fails on some population of devices, so the server links installs that share any anchor rather than demanding one hash match.
| Anchor | Platform | Reinstall | Clear data | Factory reset |
|---|---|---|---|---|
ssaid (Settings.Secure.ANDROID_ID) |
Android | survives | survives | resets |
mediaDrm (Widevine device ID) |
Android | survives | survives | resets |
appSetId |
Android | survives | survives | resets |
keychain |
iOS | survives | survives | resets |
idfv |
iOS | survives while a vendor app remains | survives | resets |
adId (opt-in) |
Android | survives | survives | survives until reset by the user |
hardwareHash |
both | survives | survives | survives (probabilistic) |
SSAID is the workhorse on Android: since API 26 it is scoped to your app's signing key, which makes it stable for your app across wipes while remaining useless for cross-app tracking. It resets on a factory reset or a signing-key change.
Raw identifiers never leave the device — every anchor is salted with a per-app key derived from your endpoint and storageNamespace and reported as a truncated SHA-256. Keep storageNamespace stable across write-key rotation or every device will look new.
Hardware signature #
Ten components (sensor inventory, GPU strings, camera optics, display geometry, CPU topology, audio config, system features, kernel, build, memory) are hashed individually rather than folded into one digest. A single whole-device hash breaks on the first OS update; independent components let the server match on overlap. The signature survives a factory reset but collides across identical phone models, so it corroborates an identity and never establishes one.
Integrity signals #
flags carries what the environment looks like: emulator, rooted, jailbroken, hooked (Frida/Xposed/Substrate), debuggerAttached, sideloaded, mockLocation, manualClock, vpn, proxy, adb. signals carries the supporting detail plus install and clock telemetry.
riskScore (0–100) is triage only. Score on the server: only it sees reinstall counts, click-to-install time and farm clustering, and only it runs on hardware the attacker does not control.
Attestation #
Heuristics can be forged; attestation cannot. Both tokens are opaque and meaningful only after server-side verification — never branch on them client-side.
// Android. Requires com.google.android.play:integrity in your app.
final token = await Jatayu.instance.requestPlayIntegrityToken(nonce: serverNonce);
// iOS. Two Apple-signed bits that survive reinstall *and* factory reset.
final token = await Jatayu.instance.requestDeviceCheckToken();
Opt-in sources #
Both are off by default because each adds an obligation your app, not the SDK, has to meet:
useAdvertisingId— addplay-services-ads-identifierand theAD_IDpermission, and declare it in Play Data Safety. Google permits joining it with other identifiers for fraud prevention, not for advertising.useGoogleServicesId— addcom.google.android.providers.gsf.permission.READ_GSERVICES.
Cost #
Collection runs off the platform thread behind a hard deadline (timeout, default 5 s) and is cached for refreshInterval (default 6 hours). It never blocks startup: the first batch ships without a fingerprint and later batches send fingerprintHash, attaching the full report only when the server replies X-Jatayu-Fingerprint: stale. Refreshing on that cadence is what catches a device rooted or hooked after launch.
Delivery, sessions, and lifecycle #
-
The SDK sends these lifecycle events on its own (constants on
JatayuEvents). Their names are fixed, andtrack()throws for any name starting with the reservedjt_prefix:Event When Properties jt_app_installFirst launch of a new installation (fresh install, or app data cleared) versionjt_app_updateFirst launch on a new app version version,previous_versionjt_app_openA session starts cold_start:truefor a process launch,falsefor a return aftersessionTimeoutjt_app_backgroundThe app leaves the foreground durationMs: foreground time since it came to the front -
jt_app_openstarts a session. Returning to the foreground aftersessionTimeout(default 30 minutes) starts a new session. The dashboard derives time in app, cold starts, installs and update adoption from these events. -
Events are queued persistently and sent in batches of 100 every
flushInterval(default 15 seconds) and when the app backgrounds. Every event carries a stable UUID and the server deduplicates retries. -
Retries use exponential backoff up to five minutes and honor
Retry-After. Failed batches stay queued;flush()retries immediately. -
The queue defaults to 1,000 events (configurable up to 10,000 via
maxQueueSize); the oldest events are dropped at capacity. Events older than 29 days are dropped before sending, matching the server's 30-day timestamp window. -
Authentication uses a 24h device session JWT. Minting first fetches a short-lived challenge (
POST /api/v1/session/challenge) and spends it onPOST /api/v1/session— the only calls that send the write key. Later calls verify statelessly server-side. Events batches bump liveness server-side, so live-user counts ride on delivery with no separate heartbeat call. Requires a server that issues challenges (Jatayu with the 0.9.0 session gate). -
Keep
storageNamespacestable across write-key rotation to preserve the installation ID, and use a distinct namespace per project if one host app initializes multiple projects. -
Shut down in tests or on full teardown with
await Jatayu.shutdown()(flushes, restores error handlers, closes owned HTTP clients). A customhttpClientis owned by its creator.
Options reference #
| Option | Default | Notes |
|---|---|---|
endpoint |
'https://api.jatayu.click' |
Jatayu server origin, HTTPS (see local-dev exception above). Omit for Jatayu Cloud; set to your self-hosted origin otherwise. |
writeKey |
required | App's public SDK key from Applications. |
appVersion |
'auto' |
'auto' reads the native app version; any other value is sent as-is. |
consent |
false |
Grant only after your app has permission to collect analytics. |
environment |
'production' |
'production' or 'staging'; selects the remote-config environment. |
storageNamespace |
'default' |
Unique per project inside one host app; keep stable across key rotation. |
flushInterval |
15 s | Minimum 1 second. |
configFetchInterval |
15 min | Background remote-config refresh cadence (matches server max-age). |
sessionTimeout |
30 min | Foreground gap that starts a new session. |
maxQueueSize |
1000 |
1–10,000; oldest events dropped at capacity. |
captureFlutterErrors |
true |
Forward Dart/Flutter errors while preserving existing handlers. |
allowInsecureLocalhost |
false |
Allow HTTP only for local-dev hosts. Never enable in production. |
linkHosts |
['link.jatayu.click'] |
Extra hosts accepted by handleLink for campaign (/l/) and referral (/r/) links. |
fingerprint |
enabled | Anti-fraud device fingerprinting; see Anti-fraud fingerprinting. |
uninstallTracking |
true |
Android background check-in and push-probe answers; see Uninstall tracking. |
httpClient |
owned client | Inject for tests or controlled networking. |
onDiagnostic |
null |
Non-sensitive diagnostics; payloads and keys are omitted. |
Example app and verification #
The example/ app exercises connect, consent, identify, groups, events, and remote config:
flutter pub get
flutter analyze
flutter test
cd example
flutter pub get
flutter run --dart-define=JATAYU_ENDPOINT=https://your-domain.com \
--dart-define=JATAYU_WRITE_KEY=your-write-key
For a local server use http://10.0.2.2:3001 on an Android emulator or http://localhost:3001 on the iOS Simulator, with allowInsecureLocalhost: true and a matching dev network policy.
Sources: SKAN verification, AdAttributionKit, Apple copy endpoints, Play Install Referrer, FCM registration management.
Support #
Report issues at https://github.com/kamaravichow/jatayu-flutter/issues.