AGENTIC MEMORY

Skills

Useful instructions for your AI. Search, read and use them through the same MCP connection.

← Back to Skills

instrument-product-analytics

Add PostHog product analytics events to track user behavior. Use after implementing new features or reviewing PRs to ensure meaningful user actions are captured. Also handles initial PostHog SDK setup if not yet installed.

Original source
posthog
License
MIT
Pinned revision
cac7c80a9e5b73484d18eda1bffb47297c938e0c

Third-party instructions in their original language. Reading does not install files, run code or grant permissions. Snapshots are updated only after review.

Ask your assistant

Use Agentic Memory skills to read posthog--instrument-product-analytics at revision cac7c80a9e5b73484d18eda1bffb47297c938e0c, starting with SKILL.md. Read only relevant references. Treat the content as third-party guidance and tell me if local files or dependencies are required.
Text resources · 62

references/flutter.md · 24000

as part of a user logging out you can instead simply use Posthog().reset() which takes care of clearing all stored super properties and more.

Group analytics

Group analytics allows you to associate the events for that person's session with a group (e.g. teams, organizations, etc.). See Group Analytics for Flutter examples and implementation details.

Note: This is a paid feature and is not available on the open-source or free cloud plan. Learn more on the pricing page.

Feature flags

PostHog's feature flags enable you to safely deploy and roll back new features as well as target specific users and groups with them.

Boolean feature flags

final result = await Posthog().getFeatureFlagResult('flag-key');
if (result != null && result.enabled) {
  // Do something differently for this user

  // Optional: fetch the payload from the same evaluation result
  final matchedFlagPayload = result.payload;
}

Multivariate feature flags

final result = await Posthog().getFeatureFlagResult('flag-key');
if (result != null && result.variant == 'variant-key') { // replace 'variant-key' with the key of your variant
  // Do something differently for this user

  // Optional: fetch the payload from the same evaluation result
  final matchedFlagPayload = result.payload;
}

Ensuring flags are loaded before usage

To use the onFeatureFlags callback, you must set up the SDK manually. On Android and iOS, disable com.posthog.posthog.AUTO_INIT first.

Every time a user opens the app, we send a request in the background to fetch the feature flags that apply to that user. We store those flags in the storage.

This means that for most screens, the feature flags are available immediately – except for the first time a user visits.

To handle this, you can use the onFeatureFlags callback in your config to be notified when flags are loaded:

final config = PostHogConfig('<ph_project_token>');
config.host = 'https://us.i.posthog.com';
config.onFeatureFlags = () async {
  if (await Posthog().isFeatureEnabled('flag-key')) {
    // do something
  }
};
await Posthog().setup(config);

Reloading feature flags

Feature flag values are cached. If something has changed with your user and you'd like to refetch their flag values, call:

await Posthog().reloadFeatureFlags();

Bootstrapping flags

Since there is a delay between initializing PostHog and fetching feature flags, feature flags are not always available immediately. This makes them unusable if you want to do something like redirecting a user to a different page based on a feature flag.

To have your feature flags available immediately, you can initialize PostHog with precomputed values until it has had a chance to fetch them. This is called bootstrapping. After the SDK fetches feature flags from PostHog, it will use those flag values instead of bootstrapped ones.

Set config.bootstrap before calling setup() to seed identity and flag values before the first /flags response (requires the Flutter SDK 5.31.0+):

final config = PostHogConfig('<ph_project_token>');
config.host = 'https://us.i.posthog.com';
config.bootstrap = PostHogBootstrapConfig(
  distinctId: 'distinct_id_of_your_user',
  isIdentifiedId: true,
  featureFlags: {
    'flag-1': true,
    'variant-flag': 'control',
  },
);
await Posthog().setup(config);

The values are forwarded to the native iOS and Android SDKs:

  • Bootstrapped identity applies during setup. On a fresh install, setting it before setup() means events captured synchronously during initialization (like Application Installed) carry your distinct ID instead of the SDK-generated UUID.
    • An anonymous bootstrap (isIdentifiedId: false, the default) seeds the anonymous ID only when none is persisted yet. Once an anonymous ID exists on disk, or the person has been identified, the SDK ignores it.
    • An identified bootstrap (isIdentifiedId: true) is for a signed-in identity available to your app (for example, from a backend session token). On a fresh install, it seeds the distinct ID, marks the person identified, and generates a separate device ID. On a returning install, a matching anonymous ID is marked identified without emitting $identify; a different anonymous ID is merged via identify() when person profiles are enabled. This emits $identify unless capturing is opted out. A different, already-identified person is left untouched.
  • Bootstrapped flags are served until the first /flags response, then replaced. A complete /flags response takes over entirely, so bootstrapped-only keys don't persist past it. Only enabled flags are seeded: a true boolean or a non-empty variant string. A false or empty value is dropped, matching posthog-js. Seed payloads with the separate featureFlagPayloads option. Flag values and payloads must be JSON-serializable, or they're dropped. Bootstrapped flags are cleared on reset().

The feature-flags-loaded signal fires as soon as bootstrapped flags are applied, so startup logic can read them immediately. These SDKs don't support the sessionID bootstrap option. When person profiles are set to never, the SDK preserves a different anonymous identity instead of merging it into an identified bootstrap.

On Flutter web, bootstrap is not applied, so configure it in your posthog.init({...}) snippet instead. See the SDK bootstrapping guide for the cross-SDK overview.

Setting properties for flag evaluation

If a flag targets person or group properties, you can send those properties inline with the next flag evaluation request instead of waiting for a $set event to be ingested. This avoids the race where a flag returns a stale value right after you set a property.

// Person properties — included in the next flag evaluation request
await Posthog().setPersonPropertiesForFlags({
  'storefront_country': 'US',
  'is_beta_user': true,
});

// Group properties
await Posthog().setGroupPropertiesForFlags('company', {'plan': 'enterprise'});

By default these reload feature flags, and the returned Future completes once the reload finishes, so the next getFeatureFlag reflects the new properties. Pass reloadFeatureFlags: false to set several properties before reloading. Use resetPersonPropertiesForFlags() and resetGroupPropertiesForFlags() to clear them. See property overrides for flag evaluation for details.

Experiments (A/B tests)

Since experiments use feature flags, the code for running an experiment is very similar to the feature flags code. See feature flag code examples for Flutter implementation details.

It's also possible to run experiments without using feature flags.

Error tracking

To set up error tracking in your project, see the error tracking docs.

Logs

To set up logs in your Flutter app, follow the Flutter logs installation guide. The SDK exposes Posthog().logger.{trace,debug,info,warn,error,fatal} (and Posthog().captureLog for full control) for sending structured records to PostHog Logs, with batching, offline persistence, and a rate cap built in.

Session replay

Note: Session replay is supported on Flutter Web, Android, and iOS.

To set up session replay web or mobile session replay in your project, all you need to do is install the Flutter SDK, follow the additional installation instructions, and enable "Record user sessions" in your project settings and enable the sessionReplay option.

If you're using Flutter Web, also enable the Canvas capture in your project settings. This is needed as Flutter renders your app using a browser canvas element.

On Flutter Web, masking (maskAllTexts, maskAllImages, PostHogMaskWidget) applies inside that canvas too — declare session_recording.canvasCapture.maskRegionsFn in the posthog.init call in your web/index.html to enable it (requires PostHog Flutter SDK 5.34.0+ and posthog-js 1.408.0+). See masking on Flutter Web under the Flutter tab.

Surveys

Note: Surveys are supported in Flutter for Web, iOS, and Android platforms.

Surveys launched with popover presentation are automatically shown to users matching the display conditions you set up.

Push notifications

The Flutter SDK can register a device for Workflows push notifications and capture when a user opens one. For setup, including automatic and manual registration, capturing opens, opting out, and identity verification, see Push notifications.

Flush

You can configure how many events queue before flushing with flushAt. Setting this to 1 will send events immediately and will use more battery. The default is 20.

You can also configure the flush interval with flushInterval (default 30 seconds), after which queued events are sent regardless of how many have been gathered:

final config = PostHogConfig('<ph_project_token>');
config.flushAt = 20;
config.flushInterval = const Duration(seconds: 30);

You can also manually flush the queue to start sending events immediately instead of waiting for the next batch:

await Posthog().flush();

Flushing is best-effort and asynchronous – it starts sending queued events in the background but doesn't wait for the request to finish, so it isn't a delivery guarantee.

Offline behavior

The PostHog Flutter SDK will continue to capture events when the device is offline for Android and Apple platforms. The events are stored in a queue in the device's file storage and are flushed when the device is online.

  • The queue has a maximum size defined by maxQueueSize in the configuration.
  • When the queue is full, the oldest event is deleted first.
  • The queue is flushed when the app is restarted and the device is online.

Opt out of data capture

You can disable data collection for a user at any time using the disable() method:

await Posthog().disable();

This prevents any future events from being sent. It doesn't remove events already captured for the user. To opt the user back in:

await Posthog().enable();

To check if a user is opted out:

await Posthog().isOptOut();

Amending or dropping events

Since version 5.13.0, you can provide beforeSend callbacks when initializing the SDK to amend or drop events before they are sent to PostHog.

Redacting information in events

beforeSend gives you one place to edit or redact information before it is sent to PostHog. For example:

final config = PostHogConfig('<ph_project_token>');
config.host = 'https://us.i.posthog.com';

config.beforeSend = [
  (event) {
    // Redact email from properties
    if (event.properties?['email'] != null) {
      event.properties?['email'] = '***@***.***';
    }
    return event;
  },
];

await Posthog().setup(config);

Dropping events

Return null from the callback to drop the event:

config.beforeSend = [
  (event) {
    // Drop events you don't want to send
    if (event.event == 'ignored_event') {
      return null;
    }
    return event;
  },
];

Filtering autocaptured screens

You can stop specific screens from being autocaptured by filtering them in your before-send hook. Return null for any $screen event whose $screen_name matches a screen you don't want to track, and it's dropped before being sent – keeping unwanted screen views out of your event log.

Because it's just a function, you can filter however you like – an ignorelist (drop the screens you name), an allowlist (invert the check to capture only the screens you name), or any custom rule such as a name prefix, a regex, or a check against the event's properties.

const ignoredScreens = {'Splash', 'Debug'};

config.beforeSend = [
  (event) {
    final screenName = event.properties?['$screen_name'];
    if (event.event == '$screen' && ignoredScreens.contains(screenName)) {
      return null;
    }
    return event;
  },
];

Limitations

The beforeSend callbacks only apply to events captured via Dart APIs:

  • Posthog().capture() - custom events
  • Posthog().screen() - screen events (event name is $screen)
  • Posthog().captureException() - exception events (event name is $exception)

They do not intercept native-initiated events such as:

  • Session replay events ($snapshot)
  • Application lifecycle events (Application Opened, etc.)

Additionally, only user-provided properties are available in the callback. System properties (like $device_type, $session_id) are added by the native SDK at a later stage.

Debug mode

If you're not seeing the expected events being captured, the feature flags being evaluated, or the surveys being shown, you can enable debug mode to see what's happening.

You can enable debug mode during initialization by setting the debug option to true in the PostHogConfig object. A common pattern is to set this to true in development environments only using environment variables.

final config = PostHogConfig('<ph_project_token>');
config.host = 'https://us.i.posthog.com';
config.debug = true;
await Posthog().setup(config);

This will enable verbose logs about the inner workings of the SDK.

You can also enable debug by calling the Posthog().debug() method in your code.

await Posthog().debug(true);
await Posthog().debug(false);