Flutter

Last updated:

|Edit this page
Which features are available in this library?
  • Event capture
  • Autocapture
  • User identification
  • Session recording
  • Feature flags
  • Group analytics

This is an optional library you can install if you're working with Flutter. It uses an internal queue to make calls fast and non-blocking. It also batches requests and flushes asynchronously, making it perfect to use in any part of your mobile app.

PostHog supports the iOS, macOS, Android and Web platforms.

Installation

PostHog is available for install via Pub.

Configuration

Set your PostHog API key and change the automatic event tracking on if you wish the library to take care of it for you.

Remember that the application lifecycle events won't have any special context set for you by the time it is initialized. If you are using a self-hosted instance of PostHog you will need to have the public hostname or IP for your instance as well.

Android

AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.posthog.posthog_flutter_example">
<application>
<activity>
[...]
</activity>
<meta-data android:name="com.posthog.posthog.API_KEY" android:value="<ph_project_api_key>" />
<!-- usually 'https://app.posthog.com' or 'https://eu.posthog.com' -->
<meta-data android:name="com.posthog.posthog.POSTHOG_HOST" android:value="<ph_instance_address>" />
<meta-data android:name="com.posthog.posthog.TRACK_APPLICATION_LIFECYCLE_EVENTS" android:value="true" />
<meta-data android:name="com.posthog.posthog.DEBUG" android:value="true" />
</application>
</manifest>

iOS/macOS

Info.plist
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
[...]
<key>com.posthog.posthog.API_KEY</key>
<string><ph_project_api_key></string>
<key>com.posthog.posthog.POSTHOG_HOST</key>
<!-- usually 'https://app.posthog.com' or 'https://eu.posthog.com' -->
<string><ph_instance_address></string>
<key>com.posthog.posthog.CAPTURE_APPLICATION_LIFECYCLE_EVENTS</key>
<true/>
<key>com.posthog.posthog.DEBUG</key>
<true/>
[...]
</dict>
</plist>

Web

index.html
<!DOCTYPE html>
<html>
<head>
...
<script>
!function(t,e){var o,n,p,r;e.__SV||(window.posthog=e,e._i=[],e.init=function(i,s,a){function g(t,e){var o=e.split(".");2==o.length&&(t=t[o[0]],e=o[1]),t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}}(p=t.createElement("script")).type="text/javascript",p.async=!0,p.src=s.api_host+"/static/array.js",(r=t.getElementsByTagName("script")[0]).parentNode.insertBefore(p,r);var u=e;for(void 0!==a?u=e[a]=[]:a="posthog",u.people=u.people||[],u.toString=function(t){var e="posthog";return"posthog"!==a&&(e+="."+a),t||(e+=" (stub)"),e},u.people.toString=function(){return u.toString(1)+".people (stub)"},o="capture identify alias people.set people.set_once set_config register register_once unregister opt_out_capturing has_opted_out_capturing opt_in_capturing reset isFeatureEnabled onFeatureFlags getFeatureFlag getFeatureFlagPayload reloadFeatureFlags group updateEarlyAccessFeatureEnrollment getEarlyAccessFeatures getActiveMatchingSurveys getSurveys".split(" "),n=0;n<o.length;n++)g(u,o[n]);e._i.push([i,s,a])},e.__SV=1)}(document,window.posthog||[]);
<!-- usually 'https://app.posthog.com' or 'https://eu.posthog.com' -->
posthog.init('<ph_project_api_key>', {api_host: '<ph_instance_address>'})
</script>
</head>
<body>
...
</body>
</html>

For more information please check: https://posthog.com/docs/libraries/js

Usage

To use this, add posthog_flutter as a dependency in your pubspec.yaml file.

Example

Dart
import 'package:flutter/material.dart';
import 'package:posthog_flutter/posthog_flutter.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
Widget build(BuildContext context) {
return MaterialApp(
navigatorObservers: [
// The PosthogObserver records screen views automatically
PosthogObserver(),
],
home: Scaffold(
appBar: AppBar(
title: Text('PostHog example app'),
),
body: Center(
child: FlatButton(
child: Text('TRACK ACTION WITH PostHog'),
onPressed: () async {
await Posthog().capture(
eventName: 'ButtonClicked',
properties: {
'foo': 'bar',
'number': 1337,
'clicked': true,
},
);
},
),
),
)
);
}
}

Capturing events

You can send custom events using capture:

Dart
await Posthog().capture(
eventName: 'user_signed_up',
);

Tip: We recommend using a '[object][verb]' format for your event names, where '[object]' is the entity that the behavior relates to, and '[verb]' is the behavior itself. For example, project created, user signed up, or invite sent.

Setting event properties

Optionally, you can also include additional information in the event by setting the properties value:

Dart
await Posthog().capture(
eventName: 'user_signed_up',
properties: {
'login_type': 'email',
'is_free_trial': true
}
);

Autocapture

PostHog autocapture automatically tracks the following events for you:

  • Application Opened - when the app is opened from a closed state or when the app comes to the foreground (e.g. from the app switcher)
  • Application Backgrounded - when the app is sent to the background by the user
  • Application Installed - when the app is installed.
  • Application Updated - when the app is updated.
  • $screen - when the user navigates (if using navigatorObservers or go_router)

Feature Flags

PostHog's feature flags enable you to safely deploy and roll back new features.

Boolean feature flags

Dart
if (await Posthog().isFeatureEnabled('flag-key')) {
// Do something differently for this user
// Optional: fetch the payload
final matchedFlagPayload = await Posthog().getFeatureFlagPayload('flag-key');
}

Multivariate feature flags

Dart
if (await Posthog().getFeatureFlag('flag-key') == 'variant-key') { // replace 'variant-key' with the key of your variant
// Do something differently for this user
// Optional: fetch the payload
final matchedFlagPayload = await Posthog().getFeatureFlagPayload('flag-key');
}

Ensuring flags are loaded before usage

Every time a user loads a screen, 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.

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:

Dart
await Posthog().reloadFeatureFlags();

Issues

Please file any issues, bugs, or feature requests in our GitHub repository.

Contributing

If you wish to contribute a change to this repo, please send a Pull Request.

Questions?

Was this page useful?

Next article

Go

This library uses an internal queue to make calls fast and non-blocking. It also batches requests and flushes asynchronously, making it perfect to use in any part of your web app or other server-side application that needs performance. Installation Capturing events Setting user properties To set user properties , include the properties you'd like to set when capturing an event: For more details on the difference between $set and $set_once , see our user properties docs . Alias Sometimes…

Read next article