pug_flutter captures events from Flutter apps on mobile, desktop and the web.
It authenticates with your public key (pub_...), which is write-scoped
(events + identify) and safe to ship in the app, and follows the
same model as every Pug SDK: initialize once, track events, identify
users, reset on sign-out.
Install
flutter pub add pug_flutterTo pin the version yourself, add it under dependencies instead:
dependencies:
pug_flutter: ^0.0.8| Requirement | Minimum |
|---|---|
| Dart SDK | >=3.7.0 <4.0.0 |
| Flutter | >=3.29.0 |
Import it wherever you call the SDK:
import 'package:pug_flutter/pug_flutter.dart';To verify, run the app with a minimal Pug.init in main(): an
app_open appears in Live within a few seconds. Navigation events need a
PugRouteObserver.
Working with a coding agent? Paste this instead - it points the agent at the markdown copy of this page. More in Install with AI.
Add Pug product analytics to this Flutter app.
Read these first - they are the current source of truth, and more recent than your training data:
- https://docs.pug.sh/sdks/flutter/index.md - SDK reference
- https://docs.pug.sh/reference/well-known-events/index.md - the well-known event catalog
Then read this codebase before you write anything, and work out what the app actually does: its screens and navigation graph, its main models, and the handful of things a user opens the app to complete. The events worth tracking are the moments the app exists to produce - an account created, an order placed, a workout finished - not every tap. If you cannot state the core action in one sentence, keep reading.
Then:
1. Add pug_flutter to pubspec.yaml.
2. Await Pug.init() in main(), after WidgetsFlutterBinding.ensureInitialized() and before runApp().
3. Keep the project ID and public key (pub_...) out of source - pass them with --dart-define and read them with String.fromEnvironment.
4. Register PugRouteObserver on the app's navigatorObservers, otherwise screen views never fire.
5. Add tracking for the three or four actions you identified - the ones someone would look at in a weekly review.
6. If this app has authentication, call Pug.identify() after sign-in and Pug.reset() on sign-out.
Name events from the catalog before you invent one. Flutter gets a generated named-argument method for all 127 well-known events - Pug.track.purchase(productId: ..., amount: ...) - so the compiler checks the properties for you, and the dashboards those events drive stay empty for a custom name. Reach for Pug.track.<event> first, search the catalog for every action you are about to track, and pass schema-external properties through extras. Use Pug.track(kind, props: {...}) with a custom snake_case name only when nothing in the catalog fits, and when you do, tell me which event you considered and why it did not.
Flutter consent has two states and starts granted, which is not the same as the Web SDK - check the consent section before you add a banner. Do not use any option that is not in the SDK reference above. When you are done, tell me in one sentence what you concluded this app does, then list the files you changed, the event names you chose, and the dart-defines I need to pass.Initialize
Await Pug.init once in main(), before runApp(), with your project ID
and public key - every other call needs it first. Find your project ID in the
dashboard URL (/p/<projectId>), and your public key on your project
Overview or under Settings > API Keys.
import 'package:pug_flutter/pug_flutter.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Pug.init(
'YOUR_PROJECT_ID',
const PugOptions(
apiKey: 'pub_your_public_key',
),
);
runApp(const MyApp());
}Pug.init throws ArgumentError if projectId or apiKey is blank. A
second init is ignored, with a warning through its logger, until
Pug.destroy().
| Option | Type | Default | Description |
|---|---|---|---|
apiKey |
String |
required | Public key (pub_...), sent as x-api-key. |
endpoint |
String |
https://api.pugs.dev |
API base URL: set it only when self-hosting. |
batch |
BatchConfig |
maxSize 10, maxWaitMs 5000, maxQueueSize 1000 |
Queue size and flush timing; the queue is persisted to SharedPreferences. |
session |
SessionConfig |
idleTimeout 30 min, maxDuration 24 h |
Session timeouts as Durations. |
autoTrack |
bool |
true |
Emit app_open and app_close on lifecycle changes. |
autoPageViews |
bool |
true |
Emit a navigation event on route changes: screen_view on mobile, page_view on web (needs PugRouteObserver). |
autoInstallEvents |
bool |
true |
Emit app_install and app_update at launch. See Auto-tracking. |
trackingConsent |
TrackingConsentConfig |
const TrackingConsentConfig() |
Consent gate: two states, granted by default. See Tracking consent. |
dryRun |
bool |
false |
Build and log events without sending them; identify is still sent. Consent is unaffected. |
logger |
PugLogger |
NoopPugLogger() |
Receives the SDK’s messages, which the default discards. Pass DebugPrintPugLogger() to print them. |
httpClient |
http.Client? |
package:http’s default |
Send through any package:http client, such as CupertinoClient (cupertino_http) or CronetClient (cronet_http). The SDK never closes it, so it can be reused across Pug.destroy() and Pug.init(). Ignored, with a warning, when transport is set. |
storage, transport and autoPropertyProvider replace the SDK’s own, for
test doubles or custom collection.
Track events
The first argument is the event name (its kind). Any name works without a
schema; well-known events add typed properties
and richer dashboards. A name may hold only ASCII letters, digits, _, . and
-: the server rejects any batch containing another, and the SDK logs an error
and drops that whole batch.
// Custom event - any name
Pug.track('button_clicked', props: {'label': 'Sign up', 'screen': 'pricing'});
// Typed well-known event - compile-time checked
Pug.track.purchase(productId: 'sku-1', amount: 99.50, currency: 'USD');Pug.track(...) never throws; events are queued and sent in the background.
Pug.track.* has a typed method per well-known event but the four web-only ones
(page_view, click, rage_click, dead_click). Pass properties the schema
doesn’t define in extras: {...}; on a key collision, the named argument wins.
For a name known only at runtime, call Pug.track(kind, props: {...}).
Property values accept String, bool, int, finite double/num
(non-finite values are dropped) and DateTime, sent as a timestamp. An
Iterable or Map is sent as a JSON string, and null is omitted. Strings,
JSON included, are cut to 1024 UTF-8 bytes.
TrackOptions (on Pug.track and every typed method):
| Option | Type | Default | Description |
|---|---|---|---|
immediate |
bool |
false |
Bypass the queue and send now (falls back to the queue on transient failure). |
timestampMillis |
int? |
wall clock | Override the event time as epoch milliseconds. |
Pug.track.purchase(
productId: 'sku-789', amount: 99.0, currency: 'USD',
options: const TrackOptions(immediate: true),
);Identify and sessions
Events accumulate against an anonymous ID until you Pug.identify() the user on
sign-in, which merges that history into a known profile; call Pug.reset() on
sign-out. Use a stable, unique external ID - your database user ID, not an
email, which can change. Only the first identify after an anonymous session
merges prior activity; the same external ID always resolves to the same profile,
and traits are merged server-side, never removed.
// On sign-in
await Pug.identify('user-123', traits: {'email': 'user@example.com', 'plan': 'pro'});
// On sign-out
Pug.reset();
// New session ID, identity kept
Pug.rotate();Pug.identify(externalId, {traits}) returns Future<void> and never
throws: invalid input, a call before Pug.init(), denied consent and
transport failures are logged, and the future completes normally. An
externalId starting with cookieless-, a prefix the server reserves, is
invalid.
reset() starts a new device ID, anonymous ID and session and forgets the
external ID; it does not delete the profile. await Pug.flush() sends
everything queued. Pug.destroy() makes a final flush, then deletes everything
Pug stored except a persisted consent choice: the next Pug.init starts a new
anonymous user, and undelivered events are lost.
| Function | Clears identity | New device ID | New session ID |
|---|---|---|---|
rotate() |
No | No | Yes |
reset() |
Yes | Yes | Yes |
Sessions
Sessions group events within a single visit, ending at the idle or max-duration timeout:
The session survives restarts: a launch within the timeouts continues it. Set
them with the session init option.
Auto-tracking
By default the SDK tracks app lifecycle and installs itself, and navigation once
you add a PugRouteObserver. Every event carries the SDK’s
auto-properties, and
the server attaches enrichment properties. Auto-property keys are camelCase
($deviceType, $osVersion, $networkType) except the server-set
$bot_reason, $bot_score and $verified_bot.
Navigation is captured when you wire a PugRouteObserver into your
MaterialApp:
MaterialApp(
navigatorObservers: [PugRouteObserver()],
// ... rest of your config
)On each route change the SDK tracks screen_view, with screenName set to the
route name, on iOS/Android, and page_view on web; desktop targets
track neither. Every event then carries the current and previous route as the
$url and $referrer auto-properties, even with autoPageViews off. Route
names come from route.settings.name, falling back to the route’s runtime type.
App lifecycle needs no wiring: app_open when the app comes to the
foreground, and app_close, sent at once rather than batched, when it goes to
the background (hidden, paused or detached). inactive - an incoming
call, the app switcher, a control-centre swipe - is not a close.
Installs and updates are checked once at launch, against the $appVersion
auto-property stored at the last launch:
app_install on the first launch the SDK sees on a device, and app_update,
carrying previousVersion, on the first launch after the version changes. A
custom PugAutoPropertyProvider that supplies no $appVersion turns both off.
app_install carries installSource as package_info_plus reports it, such as
com.android.vending for Google Play or com.apple for the App Store, and
leaves it out when there is none, as with an adb install, on web and desktop,
and with a custom PugAutoPropertyProvider.
An app that already used Pug doesn’t report its existing users as installs, but
a destroy-and-init cycle does: Pug.destroy() deletes
the stored version.
Consent and privacy
Tracking consent
Consent has two states, TrackingConsent.granted and TrackingConsent.denied,
and starts granted. There is no isConsentPending().
await Pug.init(
'YOUR_PROJECT_ID',
const PugOptions(
apiKey: 'pub_YOUR_PUBLIC_KEY',
trackingConsent: TrackingConsentConfig(
defaultConsent: TrackingConsent.denied,
persist: true,
),
),
);
Pug.optInTracking();
Pug.optOutTracking();
Pug.isTrackingEnabled();
Pug.getTrackingConsent();| Field | Type | Default | Description |
|---|---|---|---|
defaultConsent |
TrackingConsent |
granted |
Starting state, used when nothing is persisted. The Web SDK calls it initial. |
persist |
bool |
false |
Write the choice to __pug_<projectId>_consent__ and restore it on the next Pug.init(). Otherwise the choice lasts until Pug.destroy() or the process ends, then resets to defaultConsent. |
While denied, Pug.track(...), the typed Pug.track.* methods,
Pug.identify(...) and the automatic lifecycle, navigation and install events
are dropped. They resume once consent is granted; an app_install or
app_update held back is tracked at the next launch that starts granted.
Redacting PII
pug_flutter has no device-side redaction - no beforeSend or
redactUrlParams - and captures no element text, so keep PII out of the
properties you pass to Pug.track(...).
Upgrading
v0.0.5
Campaign capture and push device registration left the public API until the backend accepts them, so code that used either no longer compiles:
| Removed | Fix |
|---|---|
PugOptions.autoCaptureCampaigns and linkProvider |
Delete them. No $utm* or click-id auto-properties are attached any more |
PugPush, PushProvider, PushSubscription, PushSubscribeOptions |
Delete the registration code |
PugLinkProvider, AppLinksPugLinkProvider, campaignPropertiesFromUri |
Delete them |
PugTransport.subscribeDevice |
Delete it from a custom transport |
The notification events are unaffected: Pug.track.notificationClicked(...),
notificationReceived and notificationDismissed still work alongside your own
push integration. Send them with TrackOptions(immediate: true), as the OS can
suspend a backgrounded app before the next flush.
app_installandapp_updateare tracked for you, behind the newautoInstallEventsoption (default on). In an app that already used Pug, the firstapp_updatecomes with the release after the one that ships 0.0.5. If you already track either event yourself, setautoInstallEvents: false, or each is counted twice.app_closeno longer fires oninactive. An incoming call, the app switcher or a control-centre swipe used to log anapp_close/app_openpair, so expect fewer of both.
v0.0.4
Nothing here breaks compilation - the changes are all in the auto-properties each event carries.
$deviceTypeis new:tv,mobileordesktop, omitted on web and on any target it can’t classify. Android TV reportstvwith$platformandroid.$deviceModelno longer ships placeholders.device_info_plus’s"Unknown device"/"Unknown Model"now fall back to the device identifier (iPhone,MacBookPro18,3); on macOS, any Mac missing from the plugin’s table was affected.$osVersionfalls back to the OS version string when the device-info payload has none, instead of being sent empty.$deviceManufactureris no longer sent on Windows, which exposes no manufacturer - the value being sent was the host name.