references/flutter.md
AI agents: this is one page from PostHog's docs. Full index of Markdown docs for LLMs: https://posthog.com/llms.txt
Flutter
Canonical URL: https://posthog.com/docs/libraries/flutter
Cloud region: This page uses US Cloud hosts. For an EU Cloud project, use
https://eu.posthog.cominstead ofhttps://us.posthog.com(app host for links).
On this page
- Install with the wizard
- Installation
- Capturing events
- Identifying users
- Get the current user's distinct ID
- Alias
- Anonymous vs identified events
- Super properties
- Group analytics
- Feature flags
- Experiments (A/B tests)
- Error tracking
- Logs
- Session replay
- Surveys
- Push notifications
- Flush
- Offline behavior
- Opt out of data capture
- Amending or dropping events
- Debug mode
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.
Install with the wizard
Run this command in your project directory to add PostHog to your Flutter project. The wizard detects your framework, installs the SDK, and sets up your first events.
npx @posthog/wizard
Or set it up manually by following the rest of this guide.
Installation
PostHog is available for install via Pub.
Configuration
Set your PostHog project token and enable automatic event tracking if you want the library to capture lifecycle events 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:
pubspec.yaml
# rest of your code
dependencies:
flutter:
sdk: flutter
posthog_flutter: ^5.26.0
# rest of your code
Then complete the setup for each platform:
For Session Replay and Surveys, you must set up the SDK manually by disabling the
com.posthog.posthog.AUTO_INITmode.
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:
android/app/src/main/AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="your.package.name">
<application>
<!-- ... other configuration ... -->
<meta-data android:name="com.posthog.posthog.PROJECT_TOKEN" android:value="<ph_project_token>" />
<meta-data android:name="com.posthog.posthog.POSTHOG_HOST" android:value="https://us.i.posthog.com" /> <!-- usually 'https://us.i.posthog.com' or 'https://eu.i.posthog.com' -->
<!-- com.posthog.posthog.CAPTURE_APPLICATION_LIFECYCLE_EVENTS is enabled by default since version 5.23.0 (previously named TRACK_APPLICATION_LIFECYCLE_EVENTS, which still works as an alias) -->
<meta-data android:name="com.posthog.posthog.DEBUG" android:value="true" />
</application>
</manifest>
Or manually (more control and more configurations available):
Add your PostHog configuration to your AndroidManifest.xml file located in the android/app/src/main:
android/app/src/main/AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="your.package.name">
<application>
<!-- ... other configuration ... -->
<meta-data android:name="com.posthog.posthog.AUTO_INIT" android:value="false" />
</application>
</manifest>
In both cases, you'll also need to update the minimum Android SDK version to 23 in android/app/build.gradle:
android/app/build.gradle
// rest of your config
defaultConfig {
minSdkVersion 23
// rest of your config
}
// rest of your config
iOS setup
There are 2 ways of initializing the SDK, automatically and manually.
The SDK supports both CocoaPods and Swift Package Manager (SPM). Flutter 3.44 and later enable SPM by default. On earlier versions, or if you disabled SPM, enable it with flutter config --enable-swift-package-manager.
Automatically:
Add your PostHog configuration to the Info.plist file located in the ios/Runner directory:
ios/Runner/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>
<!-- rest of your configuration -->
<key>com.posthog.posthog.PROJECT_TOKEN</key>
<string><ph_project_token></string>
<key>com.posthog.posthog.POSTHOG_HOST</key>
<string>https://us.i.posthog.com</string>
<!-- com.posthog.posthog.CAPTURE_APPLICATION_LIFECYCLE_EVENTS is enabled by default since version 5.23.0 -->
<key>com.posthog.posthog.DEBUG</key>
<true/>
</dict>
</plist>
Or manually (more control and more configurations available):
Add your PostHog configuration to the Info.plist file located in the ios/Runner directory:
ios/Runner/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>
<!-- rest of your configuration -->
<key>com.posthog.posthog.AUTO_INIT</key>
<false/>
</dict>
</plist>
In both cases, you'll need to set the minimum platform version to iOS 13.0.
For CocoaPods projects, set it in your Podfile:
ios/Podfile
platform :ios, '13.0'
# rest of your config
For Swift Package Manager projects without a Podfile, set the Minimum Deployments version to iOS 13.0 for the Runner target in Xcode (Runner > General > Minimum Deployments). After you change Minimum Deployments, regenerate the iOS project's configuration files:
flutter build ios --config-only
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:
import 'package:flutter/material.dart';
import 'package:posthog_flutter/posthog_flutter.dart';
Future<void> main() async {
// init WidgetsFlutterBinding if not yet
WidgetsFlutterBinding.ensureInitialized();
final config = PostHogConfig('<ph_project_token>');
config.debug = true;
// captureApplicationLifecycleEvents is enabled by default since version 5.23.0
config.host = 'https://us.i.posthog.com';
await Posthog().setup(config);
runApp(MyApp());
}
Web setup
If your project has a web/ directory, this step is required. Posthog().setup() is a no-op on web, so a web build without the snippet below captures nothing.
Add your Web snippet (which you can find in your project settings) in the <header> of your web/index.html file. Write your project token into the snippet as a literal string. It's public, the same token ships to every visitor, and it needs no build-time or deploy-time injection:
web/index.html
<!DOCTYPE html>
<html>
<head>
<!-- ... other head elements ... -->
<script async>
!(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.crossOrigin = "anonymous"),
(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 || [],
Object.defineProperty(u, "toString", {
configurable: !0,
enumerable: !0,
writable: !0,
value: function (t) {
var e = "posthog";
return ("posthog" !== a && (e += "." + a), t || (e += " (stub)"), e);
},
}),
Object.defineProperty(u.people, "toString", {
configurable: !0,
enumerable: !0,
writable: !0,
value: 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 getFeatureFlagResult reloadFeatureFlags group updateEarlyAccessFeatureEnrollment getEarlyAccessFeatures getActiveMatchingSurveys getSurveys getNextSurveyStep onSessionId".split(
" ",
),
n = 0;
n < o.length;
n++
)
g(u, o[n]);
e._i.push([i, s, a]);
}),
(e.__SV = 1));
})(document, window.posthog || []);
posthog.init("<ph_project_token>", {
api_host: "https://us.i.posthog.com", // 'https://us.i.posthog.com' or 'https://eu.i.posthog.com'
defaults: "2026-08-30",
});
</script>
</head>
<!-- other elements -->
</html>
For more information please check: /docs/libraries/js
Reproducible Android builds and Shorebird
The Flutter SDK uses the native PostHog Android SDK, which depends on the PostHog core library. The Flutter package permits a range of Android SDK versions, so Gradle can select a newer native version even when your posthog_flutter version hasn't changed. Your pubspec.lock doesn't lock these Gradle dependencies.
This matters for Shorebird patches, which can't update native Android code. To keep PostHog's native dependencies consistent between a release and its patches, pin both native libraries before creating the release:
-
Inspect the versions selected for your release build. From your app's
androiddirectory, run:./gradlew :app:dependencyInsight --dependency com.posthog --configuration releaseRuntimeClasspathIf you use product flavors, replace
releaseRuntimeClasspathwith your release variant's configuration, such asproductionReleaseRuntimeClasspath. Record the selected versions ofcom.posthog:posthog-androidandcom.posthog:posthog; their version numbers differ. -
Add strict constraints to your app's
android/app/build.gradle.kts. Replace the placeholders with the versions selected together in the previous step:dependencies { constraints { implementation("com.posthog:posthog-android") { version { strictly("<android-sdk-version>") } } implementation("com.posthog:posthog") { version { strictly("<core-version>") } } } }For a Groovy
build.gradle, use the same dependency declarations withversion { strictly "<version>" }inside each constraint. A plain version declaration can still be upgraded during Gradle conflict resolution; strict constraints enforce the selected versions. -
Run the dependency report again, build your app, and verify that events arrive in PostHog. Commit the constraints and
pubspec.lock, and use the same versions for the release and its patches.
For an existing Shorebird release, use the native versions recorded for that release, not versions resolved by a fresh build today. Pinning PostHog alone doesn't freeze other plugins or your build tools. For broader dependency control, see Gradle dependency locking.
Pins also prevent automatic native bug fixes. When upgrading PostHog, review the pins, select compatible native versions together, and test event capture before shipping a new app-store release. Don't upgrade native dependencies in a Dart-only patch or force an old version below the Flutter package's required minimum.
Capturing events
You can send custom events using capture:
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, orinvite sent.
Setting event properties
Optionally, you can include additional information with the event by including a properties object:
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, once you add the
PosthogObserver - $exception - when the app throws exceptions.
Capturing screen views
Screen views aren't captured automatically. Add the PosthogObserver to your app yourself. Without it, your app sends no $screen events at all.
This works with any routing package, not just the plain Navigator API. Add the observer wherever your router takes navigator observers, as shown below for MaterialApp and go_router.
Note: Screen names come from each route's
RouteSettings.name. Most routing packages set this for you. If yours doesn't, name your routes so$screenevents are readable.
Using navigatorObservers
Add the PosthogObserver to record screen views automatically:
import 'package:flutter/material.dart';
import 'package:posthog_flutter/posthog_flutter.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
// If you're using session replay, `PostHogWidget` has to be the root, and `MaterialApp` must be the child.
return MaterialApp(
navigatorObservers: [
// The PosthogObserver records screen views automatically
PosthogObserver(),
],
...
);
}
}
Name your routes:
...
MaterialPageRoute(builder: (context) => const HomeScreenRoute(),
settings: const RouteSettings(name: 'Home Screen'),
),
...
Using go_router
Add the PosthogObserver to record screen views automatically:
import 'package:flutter/material.dart';
import 'package:posthog_flutter/posthog_flutter.dart';
import 'package:go_router/go_router.dart';
// GoRouter configuration
final _router = GoRouter(
routes: [
...
],
// The PosthogObserver records screen views automatically
observers: [PosthogObserver()],
);
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
// If you're using session replay, `PostHogWidget` has to be the root, and `MaterialApp` must be the child.
return MaterialApp.router(
routerConfig: _router,
);
}
}
Name your routes:
...
GoRoute(
name: 'Home Screen',
...
),
...
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 betweenuserPropertiesanduserPropertiesSetOnce
await Posthog().identify(
userId: emailController.text,
userProperties: {"name": "Peter Griffin", "email": "[email protected]"},
userPropertiesSetOnce: {"date_of_first_log_in": "2024-03-01"}
);
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.
await Posthog().alias(
alias: 'distinct_id',
);
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:
final config = PostHogConfig('<ph_project_token>');
config.host = 'https://us.i.posthog.com';
config.personProfiles = PostHogPersonProfiles.identifiedOnly;
How to capture identified events
If you've set the personProfiles config to PostHogPersonProfiles.identifiedOnly (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 PostHogPersonProfiles.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:
import 'package:posthog_flutter/posthog_flutter.dart';
await Posthog().register("team_id", 22);
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:
import 'package:posthog_flutter/posthog_flutter.dart';
await Posthog().unregister("team_id");
This will remove the super property and subsequent events will not include it.
If you are doing this