Flutter
Contents
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.
To start, add posthog_flutter
to your pubspec.yaml
:
Then complete the set up for each platform:
For Session replay and Surveys you must setup the SDK manually by disabling the
com.posthog.posthog.AUTO_INIT
mode.
Android setup
There are 2 ways of initializing the SDK, automatically and manually.
Automatically:
Add your PostHog configuration to your AndroidManifest.xml
file located in the android/app/src/main
:
Or manually (more control and more configurations available):
Add your PostHog configuration to your AndroidManifest.xml
file located in the android/app/src/main
:
In both cases, you'll also need to update the minimum Android SDK version to 21
in android/app/build.gradle
:
iOS setup
There are 2 ways of initializing the SDK, automatically and manually.
You'll need to have Cocoapods installed.
Automatically:
Add your PostHog configuration to the Info.plist
file located in the ios/Runner
directory:
Or manually (more control and more configurations available):
Add your PostHog configuration to the Info.plist
file located in the ios/Runner
directory:
In both cases, you'll need to set the minimum platform version to iOS 13.0 in your Podfile:
Dart setup (For manual step only)
If you followed the automatic SDK setup, then there's no more configuration needed in Dart.
If you followed the manual SDK setup:
Web setup
For Web, add your Web snippet
(which you can find in your project settings) in the <header>
of your web/index.html
file:
For more information please check: /docs/libraries/js
Capturing events
You can send custom events using capture
:
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
, orinvite sent
.
Setting event properties
Optionally, you can include additional information with the event by including a properties object:
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. You'd need to set up the
PosthogObserver
manually.)
Capturing screen views
Note: Your routes should be named. Otherwise, they won't be recorded.
Using navigatorObservers
Add the PosthogObserver
to record screen views automatically:
Name your routes:
Using go_router
Add the PosthogObserver
to record screen views automatically:
Name your routes:
Identifying users
We highly recommend reading our section on Identifying users to better understand how to correctly use this method.
Using identify
, you can associate events with specific users. This enables you to gain full insights as to how they're using your product across different sessions, devices, and platforms.
An identify
call has the following arguments:
- userId: Required. A unique identifier for your user. Typically either their email or database ID.
- userProperties: Optional. A dictionary with key:value pairs to set the person properties
- userPropertiesSetOnce: Optional. Similar to
userProperties
. See the difference betweenuserProperties
anduserPropertiesSetOnce
You should call identify
as soon as you're able to. Typically, this is after your user logs in. This ensures that events sent during your user's sessions are correctly associated with them.
When you call identify
, all previously tracked anonymous events will be linked to the user.
Get the current user's distinct ID
You may find it helpful to get the current user's distinct ID. For example, to check whether you've already called identify
for a user or not.
To do this, call PostHog().getDistinctId()
. This returns either the ID automatically generated by PostHog or the ID that has been passed by a call to identify()
.
Alias
Sometimes, you want to assign multiple distinct IDs to a single user. This is helpful when your primary distinct ID is inaccessible. For example, if a distinct ID used on the frontend is not available in your backend.
In this case, you can use alias
to assign another distinct ID to the same user.
We strongly recommend reading our docs on alias to best understand how to correctly use this method.
Anonymous vs identified events
PostHog captures two types of events: anonymous and identified
Identified events enable you to attribute events to specific users, and attach person properties. They're best suited for logged-in users.
Scenarios where you want to capture identified events are:
- Tracking logged-in users in B2B and B2C SaaS apps
- Doing user segmented product analysis
- Growth and marketing teams wanting to analyze the complete conversion lifecycle
Anonymous events are events without individually identifiable data. They're best suited for web analytics or apps where users aren't logged in.
Scenarios where you want to capture anonymous events are:
- Tracking a marketing website
- Content-focused sites
- B2C apps where users don't sign up or log in
Under the hood, the key difference between identified and anonymous events is that for identified events we create a person profile for the user, whereas for anonymous events we do not.
Important: Due to the reduced cost of processing them, anonymous events can be up to 4x cheaper than identified ones, so we recommended you only capture identified events when needed.
How to capture anonymous events
The Flutter SDK captures anonymous events by default. However, this may change depending on your personProfiles
config when initializing PostHog:
personProfiles: PostHogPersonProfiles.identifiedOnly
(recommended) (default) - Anonymous events are captured by default. PostHog only captures identified events for users where person profiles have already been created.personProfiles: PostHogPersonProfiles.always
- Capture identified events for all events.personProfiles: PostHogPersonProfiles.never
- Capture anonymous events for all events.
For example:
How to capture identified events
If you've set the personProfiles
config to IDENTIFIED_ONLY
(the default option), anonymous events are captured by default. Then, to capture identified events, call any of the following functions:
When you call any of these functions, it creates a person profile for the user. Once this profile is created, all subsequent events for this user will be captured as identified events.
Alternatively, you can set personProfiles
to ALWAYS
to capture identified events by default.
Super properties
Super properties are properties associated with events that are set once and then sent with every capture
call, be it a $screen
, or anything else.
They are set using Posthog().register
, which takes a key and value, and they persist across sessions.
For example, take a look at the following call:
The call above ensures that every event sent by the user will include "team_id": 22
. This way, if you filtered events by property using team_id = 22
, it would display all events captured on that user after the Posthog().register
call, since they all include the specified super property.
However, please note that this does not store properties against the User, only against their events. To store properties against the User object, you should use Posthog().identify
. More information on this can be found on the Sending User Information section.
Removing stored super properties
Super properties are persisted across sessions so you have to explicitly remove them if they are no longer relevant. In order to stop sending a super property with events, you can use Posthog().unregister
, like so:
This will remove the super property and subsequent events will not include it.
If you are doing this 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.). Read the Group Analytics guide for more information.
Note: This is a paid feature and is not available on the open-source or free cloud plan. Learn more here.
- Associate the events for this session with a group
- Associate the events for this session with a group AND update the properties of that group
The name
is a special property which is used in the PostHog UI for the name of the group. If you don't specify a name
property, the group ID will be used instead.
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
Multivariate feature flags
Ensuring flags are loaded before usage
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.
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:
Session replay
Note: Session replay is supported on the Flutter Web, Android and iOS environments.
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.
Surveys
Note: Surveys is 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.
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:
This prevents any future events from being sent. It doesn’t remove events already captured for the user. To opt the user back in:
To check if a user is opted out: