### Installation Examples Source: https://github.com/posthog/posthog-flutter/blob/main/_autodocs/api-reference/posthog-observer.md Provides code examples for integrating `PosthogObserver` into a Flutter application using `MaterialApp` or `GoRouter`. ```APIDOC ## Installation ### MaterialApp ```dart MaterialApp( navigatorObservers: [PosthogObserver()], home: MyApp(), ); ``` ### GoRouter ```dart GoRouter( observers: [PosthogObserver()], routes: [...], ); ``` ``` -------------------------------- ### Example: Basic PosthogObserver Setup Source: https://github.com/posthog/posthog-flutter/blob/main/_autodocs/api-reference/posthog-observer.md Demonstrates how to create a PosthogObserver with a custom name extractor and route filter, and then add it to a MaterialApp's navigator observers. ```dart final observer = PosthogObserver( nameExtractor: (settings) => settings.name, routeFilter: (route) => route is PageRoute, ); MaterialApp( navigatorObservers: [observer], // ... other settings ); ``` -------------------------------- ### Build example app on supported platforms Source: https://github.com/posthog/posthog-flutter/blob/main/CONTRIBUTING.md Verify that the example application builds correctly on all supported platforms. Run these commands from the repository root. ```bash flutter pub get cd example flutter build ios --simulator --no-codesign flutter build macos flutter build apk flutter build web ``` -------------------------------- ### Setup PostHog SDK Source: https://github.com/posthog/posthog-flutter/blob/main/_autodocs/api-reference/posthog.md Initializes the PostHog SDK with configuration including project token, host, and session replay settings. Completes when platform setup is finished. ```dart final config = PostHogConfig('your-project-token'); config.host = 'https://your-posthog-instance.com'; config.sessionReplay = true; config.errorTrackingConfig.captureFlutterErrors = true; await Posthog().setup(config); ``` -------------------------------- ### Complete PostHog Flutter Setup with Session Replay Source: https://github.com/posthog/posthog-flutter/blob/main/_autodocs/api-reference/posthog-widget.md This snippet demonstrates the complete setup for the PostHog Flutter Widget, including configuring the API key, host, and enabling session replay with custom settings. It also shows how to integrate the PostHogWidget and PosthogObserver into a Flutter application. ```dart import 'package:flutter/material.dart'; import 'package:posthog_flutter/posthog_flutter.dart'; void main() async { final config = PostHogConfig('phc_your_token'); config.host = 'https://your-posthog-instance.com'; // Enable session replay config.sessionReplay = true; config.sessionReplayConfig.maskAllTexts = true; config.sessionReplayConfig.maskAllImages = false; config.sessionReplayConfig.throttleDelay = Duration(milliseconds: 500); config.sessionReplayConfig.sampleRate = 1.0; // Record all sessions await Posthog().setup(config); runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return PostHogWidget( child: MaterialApp( navigatorObservers: [PosthogObserver()], home: HomePage(), routes: { '/details': (context) => DetailsPage(), }, ), ); } } class HomePage extends StatefulWidget { @override State createState() => _HomePageState(); } class _HomePageState extends State { late Future _replayActive; @override void initState() { super.initState(); _replayActive = Posthog().isSessionReplayActive(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text('Home')), body: FutureBuilder( future: _replayActive, builder: (context, snapshot) { return Column( children: [ if (snapshot.data == true) Container( color: Colors.yellow, padding: EdgeInsets.all(8), child: Text('Session is being recorded'), ), ElevatedButton( onPressed: () { Navigator.pushNamed(context, '/details'); }, child: Text('Go to Details'), ), ], ); }, ), ); } } class DetailsPage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text('Details')), body: Column( children: [ // Regular content is captured in replay Text('Visible in replay'), // This content is masked PostHogMaskWidget( child: Card( child: Padding( padding: EdgeInsets.all(16), child: Text('Sensitive data (masked in replay)'), ), ), ), ], ), ); } } ``` -------------------------------- ### setup Source: https://github.com/posthog/posthog-flutter/blob/main/_autodocs/api-reference/posthog.md Initializes the PostHog SDK with the provided configuration. This method must be called before any other SDK operations. ```APIDOC ## setup ### Description Initializes the PostHog SDK with the provided configuration. This method must be called before any other SDK operations. ### Method `Future setup(PostHogConfig config)` ### Endpoint N/A ### Parameters #### Request Body - **config** (PostHogConfig) - Required - Configuration object containing project token, host, and other settings ### Request Example ```dart final config = PostHogConfig('your-project-token'); config.host = 'https://your-posthog-instance.com'; config.sessionReplay = true; config.errorTrackingConfig.captureFlutterErrors = true; await Posthog().setup(config); ``` ### Response #### Success Response (void) Completes when platform setup has finished. ### Throws No exceptions thrown directly. If `config.projectToken` is empty, setup is skipped and a debug message is printed. ``` -------------------------------- ### Start Session Recording Source: https://github.com/posthog/posthog-flutter/blob/main/_autodocs/api-reference/posthog-widget.md Use `Posthog().startSessionRecording()` to resume the current session recording or start a new one by setting `resumeCurrent` to false. ```dart // Resume current session await Posthog().startSessionRecording(); // Start a new session await Posthog().startSessionRecording(resumeCurrent: false); ``` -------------------------------- ### Initialize PostHogConfig with Project Token Source: https://github.com/posthog/posthog-flutter/blob/main/_autodocs/api-reference/posthog-config.md Create a PostHogConfig instance with your project token and customize host and session replay before setup. ```dart final config = PostHogConfig('phc_your_token'); config.host = 'https://your-posthog-instance.com'; config.sessionReplay = true; await Posthog().setup(config); ``` -------------------------------- ### Development Setup Configuration Source: https://github.com/posthog/posthog-flutter/blob/main/_autodocs/configuration.md Configure the SDK for a local development environment, typically pointing to a local PostHog instance and enabling debug logs. ```dart final config = PostHogConfig('phc_dev_token'); config.host = 'http://localhost:8000'; config.debug = true; config.optOut = false; // Capture events in dev ``` -------------------------------- ### Complete Error Handling Setup in Flutter Source: https://github.com/posthog/posthog-flutter/blob/main/_autodocs/errors.md Configure PostHog for comprehensive error tracking, including Flutter errors, platform dispatcher errors, isolate errors, and native exceptions. This example also shows how to set up in-app frame detection and handle errors within the Flutter framework. ```dart import 'package:flutter/material.dart'; import 'package:posthog_flutter/posthog_flutter.dart'; void main() { runZonedGuarded( () async { // Initialize PostHog with error tracking final config = PostHogConfig('phc_your_token'); config.errorTrackingConfig.captureFlutterErrors = true; config.errorTrackingConfig.capturePlatformDispatcherErrors = true; config.errorTrackingConfig.captureIsolateErrors = true; config.errorTrackingConfig.captureNativeExceptions = true; // Configure in-app frame detection config.errorTrackingConfig.inAppIncludes.addAll([ 'package:my_app', 'package:my_internal_package', ]); await Posthog().setup(config); runApp(MyApp()); }, (error, stackTrace) async { // Handle errors from runZonedGuarded await Posthog().captureRunZonedGuardedError( error: error, stackTrace: stackTrace, properties: { 'source': 'runZonedGuarded', }, ); }, ); } class MyApp extends StatefulWidget { @override State createState() => _MyAppState(); } class _MyAppState extends State { @override void initState() { super.initState(); // Set up FlutterError handler FlutterError.onError = (FlutterErrorDetails details) { if (details.silent) { return; } Posthog().captureException( error: details.exception, stackTrace: details.stack, properties: { 'source': 'FlutterError', 'context': details.context?.toString(), }, ); }; } @override Widget build(BuildContext context) { return PostHogWidget( child: MaterialApp( navigatorObservers: [PosthogObserver()], home: SafeArea( child: HomePage(), ), ), ); } } class HomePage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text('Home')), body: ElevatedButton( onPressed: () async { // Manually capture an exception try { await riskyOperation(); } catch (error, stackTrace) { await Posthog().captureException( error: error, stackTrace: stackTrace, properties: {'operation': 'riskyOperation'}, ); ScaffoldMessenger.of(context).showSnackBar( SnackBar(content: Text('Error occurred')), ); } }, child: Text('Perform Risky Operation'), ), ); } Future riskyOperation() async { // Simulate an error throw Exception('Something went wrong!'); } } ``` -------------------------------- ### Start Session Recording Source: https://github.com/posthog/posthog-flutter/blob/main/_autodocs/api-reference/posthog.md Initiates session recording for mobile replay. You can choose to resume the current session or start a new one. ```dart // Resume current session recording await Posthog().startSessionRecording(); // Start a new recording session await Posthog().startSessionRecording(resumeCurrent: false); ``` -------------------------------- ### Install PosthogObserver for Surveys Source: https://github.com/posthog/posthog-flutter/blob/main/_autodocs/api-reference/posthog-widget.md Optionally, install PosthogObserver as a navigator observer for enhanced survey functionality within your app. ```dart MaterialApp( navigatorObservers: [PosthogObserver()], ) ``` -------------------------------- ### Initialize PostHog SDK with Full Configuration Source: https://github.com/posthog/posthog-flutter/blob/main/_autodocs/configuration.md This example demonstrates a comprehensive initialization of the PostHog SDK, including custom host, event capture settings, feature flags, session replay, error tracking, and before-send callbacks. ```dart import 'package:flutter/material.dart'; import 'package:posthog_flutter/posthog_flutter.dart'; void main() async { // Create configuration final config = PostHogConfig('phc_your_project_token'); // Set custom host (optional) config.host = 'https://your-posthog-instance.com'; // Configure event capture config.flushAt = 50; config.maxQueueSize = 2000; config.captureApplicationLifecycleEvents = true; // Configure feature flags config.preloadFeatureFlags = true; config.onFeatureFlags = () { print('Feature flags loaded'); }; // Configure session replay config.sessionReplay = true; config.sessionReplayConfig.maskAllTexts = true; config.sessionReplayConfig.maskAllImages = false; config.sessionReplayConfig.throttleDelay = Duration(milliseconds: 500); config.sessionReplayConfig.sampleRate = 0.5; // 50% of sessions // Configure error tracking config.errorTrackingConfig.captureFlutterErrors = true; config.errorTrackingConfig.captureNativeExceptions = true; config.errorTrackingConfig.inAppIncludes.addAll([ 'package:my_app', 'package:my_company_utils', ]); // Configure before-send callbacks config.beforeSend = [ (event) { // Remove sensitive properties event.properties?.remove('api_key'); return event; }, (event) { // Drop specific events if (event.event.startsWith('internal_')) { return null; } return event; }, ]; // Initialize the SDK await Posthog().setup(config); runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return PostHogWidget( child: MaterialApp( navigatorObservers: [PosthogObserver()], home: HomePage(), ), ); } } ``` -------------------------------- ### Install PostHog Flutter SDK Source: https://github.com/posthog/posthog-flutter/blob/main/_autodocs/README.md Add the PostHog Flutter SDK to your project's pubspec.yaml file. ```yaml dependencies: posthog_flutter: ^5.26.0 ``` -------------------------------- ### Enable Swift Package Manager and build Source: https://github.com/posthog/posthog-flutter/blob/main/CONTRIBUTING.md Configure Flutter to use Swift Package Manager and then build the example app. This is useful for exercising SPM locally. ```bash flutter config --enable-swift-package-manager flutter pub get cd example flutter build ios --simulator --no-codesign flutter build macos ``` -------------------------------- ### Start with Opt-Out Enabled Source: https://github.com/posthog/posthog-flutter/blob/main/_autodocs/api-reference/posthog-config.md Initialize the SDK with data collection disabled. Use Posthog().enable() and Posthog().disable() to change this state at runtime. ```dart config.optOut = true; // Start with tracking disabled ``` -------------------------------- ### Production Setup Configuration Source: https://github.com/posthog/posthog-flutter/blob/main/_autodocs/configuration.md Configure the SDK for a production environment, using your production token, a valid PostHog host, and enabling essential features like session replay and lifecycle event capture. ```dart final config = PostHogConfig('phc_prod_token'); config.host = 'https://us.posthog.com'; config.debug = false; config.sessionReplay = true; config.captureApplicationLifecycleEvents = true; ``` -------------------------------- ### Example Screen Event Tracking Source: https://github.com/posthog/posthog-flutter/blob/main/_autodocs/api-reference/posthog-observer.md Demonstrates how to manually send a screen event with a specific name. This is useful when automatic tracking is not sufficient or for custom screen naming. ```dart await Posthog().screen(screenName: 'product_detail'); // Or with custom name extractor await Posthog().screen(screenName: 'product_123'); ``` -------------------------------- ### startSessionRecording Source: https://github.com/posthog/posthog-flutter/blob/main/_autodocs/api-reference/posthog.md Initiates session recording for mobile replay, allowing you to capture user interactions. You can choose to resume the current session or start a new one. ```APIDOC ## startSessionRecording ### Description Starts session recording for mobile replay. ### Method `Future startSessionRecording({bool resumeCurrent = true})` ### Parameters #### Path Parameters * **resumeCurrent** (bool) - Optional - `true` to resume recording the current session, `false` to start a new session (Default: `true`) ### Return `Future` — Completes when the start request has been sent. ### Behavior - Has no effect if PostHog is not enabled or session replay is disabled in project settings - Updates internal tracking of session recording state ### Example ```dart // Resume current session recording await Posthog().startSessionRecording(); // Start a new recording session await Posthog().startSessionRecording(resumeCurrent: false); ``` ``` -------------------------------- ### Run Apple Example in Release Mode Source: https://github.com/posthog/posthog-flutter/blob/main/example/README.md Runs the Flutter application in release mode on an Apple device. Requires device pairing and a valid Xcode team for signing. ```bash # needs device pairing - enable debug mode on the device # make sure you have a valid team in Xcode, go to Signing & Capabilities flutter devices flutter run --release -d Manoel --verbose # replace Manoel with your device's name/id ``` -------------------------------- ### Custom Route Filter Example Source: https://github.com/posthog/posthog-flutter/blob/main/_autodocs/api-reference/posthog-observer.md An example of a custom PostHogRouteFilter that tracks PageRoutes but excludes full-screen dialogs and bottom sheets. ```dart PosthogObserver( routeFilter: (route) { // Only track PageRoutes, but exclude dialog and bottom sheet routes if (route is PageRoute) { return !route.fullscreenDialog; // Skip full-screen dialogs } return false; }, ); ``` -------------------------------- ### Initialize PostHog SDK Source: https://github.com/posthog/posthog-flutter/blob/main/example/web/index.html Initializes the PostHog SDK with your project's API key and configuration. Ensure you replace 'phc_...' with your actual API key and 'https://us.i.posthog.com' with your API host if different. This example disables session recording, debug logging, and other features. ```javascript posthog.init( 'phc_6lqCaCDCBEWdIGieihq5R2dZpPVbAUFISA75vFZow06', { api_host:'https://us.i.posthog.com', debug: true, disable_session_recording: true, autocapture: false, disable_surveys: true, rageclick: false, enable_heatmaps: false, capture_dead_clicks: false, capture_pageview: false, capture_pageleave: false, capture_exceptions: false, } ) ``` -------------------------------- ### Complete PostHog Flutter SDK Setup Source: https://github.com/posthog/posthog-flutter/blob/main/_autodocs/README.md Initialize the PostHog SDK with a configuration object, setting up feature flags, session replay, error tracking, and before-send callbacks. This is typically done in the main function of your application. ```dart void main() async { final config = PostHogConfig('phc_token'); config.host = 'https://posthog.example.com'; // Feature flags config.preloadFeatureFlags = true; config.onFeatureFlags = () { print('Flags loaded'); }; // Session replay config.sessionReplay = true; config.sessionReplayConfig.maskAllTexts = true; config.sessionReplayConfig.sampleRate = 0.5; // Error tracking config.errorTrackingConfig.captureFlutterErrors = true; config.errorTrackingConfig.captureNativeExceptions = true; // Before-send config.beforeSend = [ (event) { event.properties?.remove('api_key'); return event; }, ]; await Posthog().setup(config); runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return PostHogWidget( child: MaterialApp( navigatorObservers: [PosthogObserver()], home: HomePage(), ), ); } } ``` -------------------------------- ### Performance-Optimized Setup Configuration Source: https://github.com/posthog/posthog-flutter/blob/main/_autodocs/configuration.md Optimize SDK performance by adjusting event flushing parameters, batch sizes, and session replay settings like throttle delay and sample rate. ```dart final config = PostHogConfig('phc_token'); config.flushAt = 100; config.flushInterval = Duration(seconds: 60); config.maxBatchSize = 100; config.sessionReplayConfig.throttleDelay = Duration(seconds: 2); config.sessionReplayConfig.sampleRate = 0.1; // 10% of sessions ``` -------------------------------- ### Posthog Singleton Entry Point Source: https://github.com/posthog/posthog-flutter/blob/main/_autodocs/types.md The main singleton entry point for the PostHog Flutter SDK. Use this for setup, identifying users, and capturing events. ```dart class Posthog { factory Posthog(); Future setup(PostHogConfig config); Future identify({ required String userId, Map? userProperties, Map? userPropertiesSetOnce, }); Future capture({ required String eventName, Map? properties, Map? userProperties, Map? userPropertiesSetOnce, }); // ... and many more methods } ``` -------------------------------- ### Custom Name Extractor Example Source: https://github.com/posthog/posthog-flutter/blob/main/_autodocs/api-reference/posthog-observer.md An example of a custom ScreenNameExtractor that derives screen names from route arguments, specifically for a product detail route. ```dart PosthogObserver( nameExtractor: (settings) { // Extract screen name from route arguments if (settings.name == '/product') { final args = settings.arguments as Map?; final productId = args?['id'] as String?; return productId != null ? 'product_$productId' : 'product'; } return settings.name; }, ); ``` -------------------------------- ### BeforeSendCallback Example Source: https://github.com/posthog/posthog-flutter/blob/main/_autodocs/types.md An example of a BeforeSendCallback that intercepts events. This callback drops events named 'sensitive_event' by returning null, otherwise it returns the event. ```dart final callback = (PostHogEvent event) { if (event.event == 'sensitive_event') { return null; // Drop the event } return event; }; ``` -------------------------------- ### OnFeatureFlagsCallback Example Source: https://github.com/posthog/posthog-flutter/blob/main/_autodocs/types.md An example of an OnFeatureFlagsCallback. This callback is invoked after feature flags load and checks if 'my_flag' is enabled to potentially initialize a feature. ```dart config.onFeatureFlags = () { final enabled = Posthog().isFeatureEnabled('my_flag'); if (enabled) { // Initialize feature } }; ``` -------------------------------- ### PostHogFeatureFlagResult toString Example Source: https://github.com/posthog/posthog-flutter/blob/main/_autodocs/api-reference/feature-flags.md Shows the string representation of a PostHogFeatureFlagResult object. This is useful for debugging and logging. ```dart final result = await Posthog().getFeatureFlagResult('my_flag'); print(result); // PostHogFeatureFlagResult(key: my_flag, enabled: true, variant: control, payload: {...}) ``` -------------------------------- ### PostHogFeatureFlagResult Equality Example Source: https://github.com/posthog/posthog-flutter/blob/main/_autodocs/api-reference/feature-flags.md Demonstrates equality comparison for PostHogFeatureFlagResult objects. Two results are considered equal if their key, enabled status, and variant match. ```dart final result1 = PostHogFeatureFlagResult( key: 'my_flag', enabled: true, variant: 'control', ); final result2 = PostHogFeatureFlagResult( key: 'my_flag', enabled: true, variant: 'control', ); assert(result1 == result2); ``` -------------------------------- ### optOut Property Source: https://github.com/posthog/posthog-flutter/blob/main/_autodocs/api-reference/posthog-config.md Determines whether the SDK starts with data collection disabled. Defaults to false. ```APIDOC ## optOut Property ### Description Whether the SDK starts with data collection disabled. ### Default `false` ### Behavior When `true`, the SDK initializes in a disabled state. Use `Posthog().disable()` and `Posthog().enable()` to change this at runtime. ### Example ```dart config.optOut = true; // Start with tracking disabled ``` ``` -------------------------------- ### Posthog Class Source: https://github.com/posthog/posthog-flutter/blob/main/_autodocs/types.md The main singleton entry point for the PostHog Flutter SDK, providing methods for setup, identify, and capture events. ```APIDOC ## Posthog Class ### Description The main singleton entry point for the PostHog Flutter SDK. ### Methods #### `setup(PostHogConfig config)` Initializes the PostHog SDK with the provided configuration. #### `identify({required String userId, Map? userProperties, Map? userPropertiesSetOnce})` Associates a user with the given user ID and properties. #### `capture({required String eventName, Map? properties, Map? userProperties, Map? userPropertiesSetOnce})` Captures an event with the given name and properties. ``` -------------------------------- ### Privacy-Focused Setup Configuration Source: https://github.com/posthog/posthog-flutter/blob/main/_autodocs/configuration.md Configure the SDK with a focus on user privacy, by setting person profiles to `identifiedOnly`, masking text and images in session replays, and specifying which packages to include in error tracking. ```dart final config = PostHogConfig('phc_token'); config.personProfiles = PostHogPersonProfiles.identifiedOnly; config.sessionReplayConfig.maskAllTexts = true; config.sessionReplayConfig.maskAllImages = true; config.errorTrackingConfig.inAppIncludes = ['package:my_app']; ``` -------------------------------- ### host Property Source: https://github.com/posthog/posthog-flutter/blob/main/_autodocs/api-reference/posthog-config.md Sets or gets the PostHog ingestion host URL. Defaults to 'https://us.i.posthog.com'. ```APIDOC ## host Property ### Description The PostHog ingestion host URL. ### Default `'https://us.i.posthog.com'` ### Behavior - Setting to a blank value reverts to the default host - Whitespace is trimmed automatically ### Example ```dart config.host = 'https://your-posthog-instance.com'; config.host = 'https://eu.posthog.com'; ``` ``` -------------------------------- ### Initialize PostHogWidget for Session Replay Source: https://github.com/posthog/posthog-flutter/blob/main/_autodocs/api-reference/posthog-widget.md Wrap your app's root widget with PostHogWidget and enable session replay in the PostHogConfig. This setup is required for capturing session replays. ```dart void main() async { final config = PostHogConfig('your-token'); config.sessionReplay = true; await Posthog().setup(config); runApp( PostHogWidget( child: MyApp(), ), ); } ``` -------------------------------- ### Start and Stop Session Recording Source: https://github.com/posthog/posthog-flutter/blob/main/_autodocs/configuration.md Manually control the session recording feature. Use `startSessionRecording()` to begin recording and `stopSessionRecording()` to halt it. ```dart await Posthog().startSessionRecording(); await Posthog().stopSessionRecording(); ``` -------------------------------- ### projectToken Property Source: https://github.com/posthog/posthog-flutter/blob/main/_autodocs/api-reference/posthog-config.md Gets the PostHog project token. This is a read-only property. ```APIDOC ## projectToken Property ### Description Your PostHog project token (read-only). ### Example ```dart print('Using token: ${config.projectToken}'); ``` ### Note The `apiKey` property is deprecated and provided for backward compatibility. Use `projectToken` instead. ``` -------------------------------- ### Surveys Configuration Source: https://github.com/posthog/posthog-flutter/blob/main/_autodocs/api-reference/posthog-config.md Enable or disable surveys for the application. Requires `PosthogObserver` to be installed and may need re-initialization after `Posthog().close()`. ```APIDOC ## surveys Whether to enable surveys for the app. ```dart bool surveys = true ``` ### Default `true` ### Requirements - `PosthogObserver` must be installed for surveys to display - After calling `Posthog().close()`, surveys require re-initialization and a navigation event to display again - On Flutter web, surveys use the JavaScript Web SDK instead ### Example ```dart config.surveys = false; ``` ``` -------------------------------- ### Full Flutter App Integration with PosthogObserver Source: https://github.com/posthog/posthog-flutter/blob/main/_autodocs/api-reference/posthog-observer.md Provides a complete example of setting up Posthog Flutter SDK and integrating PosthogObserver into the MaterialApp's navigatorObservers. This enables automatic screen tracking and survey functionality. ```dart import 'package:flutter/material.dart'; import 'package:posthog_flutter/posthog_flutter.dart'; void main() async { final config = PostHogConfig('your-token'); config.host = 'https://your-posthog.com'; await Posthog().setup(config); runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( navigatorObservers: [PosthogObserver()], home: HomePage(), ); } } class HomePage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text('Home')), body: ElevatedButton( onPressed: () { // Navigate to details Navigator.of(context).pushNamed('/details'); // PosthogObserver automatically sends: $screen event for '/details' }, child: Text('Go to Details'), ), ); } } ``` -------------------------------- ### preloadFeatureFlags Property Source: https://github.com/posthog/posthog-flutter/blob/main/_autodocs/api-reference/posthog-config.md Determines whether to load feature flags when the SDK starts. Defaults to true. ```APIDOC ## preloadFeatureFlags Property ### Description Whether to load feature flags when the SDK starts. ### Default `true` ### Example ```dart config.preloadFeatureFlags = false; // Load flags manually ``` ``` -------------------------------- ### PostHogFeatureFlagResult fromMap Example (Internal Use) Source: https://github.com/posthog/posthog-flutter/blob/main/_autodocs/api-reference/feature-flags.md Illustrates creating a PostHogFeatureFlagResult from a map, typically used internally to parse responses from native SDKs. It handles fallback keys and default values. ```dart // This is typically called internally by the platform interface final response = {'enabled': true, 'variant': 'treatment', 'payload': {...}}; final result = PostHogFeatureFlagResult.fromMap(response, 'my_flag'); assert(result?.key == 'my_flag'); assert(result?.enabled == true); ``` -------------------------------- ### Get Feature Flag Result Example Source: https://github.com/posthog/posthog-flutter/blob/main/_autodocs/api-reference/feature-flags.md Retrieves the complete feature flag result, including its key, enabled status, variant, and payload. This is useful for detailed flag analysis. ```dart final result = await Posthog().getFeatureFlagResult('my_flag'); print('Flag key: ${result?.key}'); ``` -------------------------------- ### Handle Unhandled Exceptions with runZonedGuarded Source: https://github.com/posthog/posthog-flutter/blob/main/_autodocs/errors.md Use runZonedGuarded to wrap your application's main execution flow and catch any unhandled errors. This setup ensures that errors are captured by PostHog and optionally logged to other services. ```dart void main() { runZonedGuarded( () async { final config = PostHogConfig('phc_token'); await Posthog().setup(config); runApp(MyApp()); }, (error, stackTrace) async { await Posthog().captureRunZonedGuardedError( error: error, stackTrace: stackTrace, ); // Log to external service if needed logToExternalService(error, stackTrace); }, ); // Also set up PlatformDispatcher error handler for Dart runtime errors if (!kIsWeb) { PlatformDispatcher.instance.onError = (error, stack) { Posthog().captureException( error: error, stackTrace: stack, ); return true; // Error was handled }; } } ``` -------------------------------- ### Initialize PostHog SDK Source: https://github.com/posthog/posthog-flutter/blob/main/_autodocs/README.md Initialize the PostHog SDK with your project token and host. Wrap your root widget with PostHogWidget and add PosthogObserver to your navigator observers for automatic screen tracking. ```dart import 'package:posthog_flutter/posthog_flutter.dart'; void main() async { final config = PostHogConfig('your-project-token'); config.host = 'https://your-posthog-instance.com'; await Posthog().setup(config); runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return PostHogWidget( child: MaterialApp( navigatorObservers: [PosthogObserver()], home: HomePage(), ), ); } } ``` -------------------------------- ### Enter Pre-release Mode Source: https://github.com/posthog/posthog-flutter/blob/main/RELEASING.md Use these commands to enter and exit pre-release mode for alpha, beta, or RC versions. After entering pre-release mode, run `pnpm changeset version` to prepare the release. ```bash pnpm changeset pre enter alpha # or beta, rc ``` ```bash pnpm changeset version ``` ```bash pnpm changeset pre exit ``` -------------------------------- ### SDK Lifecycle Methods Source: https://github.com/posthog/posthog-flutter/blob/main/_autodocs/MANIFEST.md Methods for initializing and closing the PostHog SDK. ```APIDOC ## Lifecycle Methods ### `setup()` #### Description Initializes the PostHog SDK. ### `close()` #### Description Closes the PostHog SDK and flushes any pending events. ``` -------------------------------- ### Add a Changeset Source: https://github.com/posthog/posthog-flutter/blob/main/RELEASING.md Run this command to create a new changeset file. You will be prompted to select the version bump type and write a summary of the changes. ```bash pnpm changeset ``` -------------------------------- ### GoRouter Integration Source: https://github.com/posthog/posthog-flutter/blob/main/_autodocs/api-reference/posthog-observer.md Demonstrates how to integrate PosthogObserver with GoRouter by providing it in the observers list. ```dart GoRouter( observers: [PosthogObserver()], routes: [...], ); ``` -------------------------------- ### Get Current Distinct ID Source: https://github.com/posthog/posthog-flutter/blob/main/_autodocs/api-reference/posthog.md Retrieves the unique identifier for the current user. This ID is used to track user activity. ```dart final distinctId = await Posthog().getDistinctId(); print('User ID: $distinctId'); ``` -------------------------------- ### Feature Flag Payload Example Source: https://github.com/posthog/posthog-flutter/blob/main/_autodocs/api-reference/feature-flags.md Retrieves and utilizes the JSON payload associated with a feature flag or its variant. This allows for dynamic configuration of features. ```dart final result = await Posthog().getFeatureFlagResult('banner_config'); if (result?.payload is Map) { final config = result!.payload as Map; final title = config['title'] as String?; final color = config['color'] as String?; // Use payload to configure the banner } ``` -------------------------------- ### PostHogConfig Constructor Source: https://github.com/posthog/posthog-flutter/blob/main/_autodocs/configuration.md Initialize the PostHog SDK with your project token and optional callbacks for feature flags and event modification. ```dart PostHogConfig( String projectToken, { OnFeatureFlagsCallback? onFeatureFlags, List? beforeSend, } ) ``` -------------------------------- ### Disable Surveys Source: https://github.com/posthog/posthog-flutter/blob/main/_autodocs/api-reference/posthog-config.md Set `surveys` to `false` to disable the survey feature. Ensure `PosthogObserver` is installed and re-initialize surveys after calling `Posthog().close()`. ```dart config.surveys = false; ``` -------------------------------- ### Disable Preloading Feature Flags Source: https://github.com/posthog/posthog-flutter/blob/main/_autodocs/api-reference/posthog-config.md Set to false to prevent feature flags from being loaded automatically when the SDK starts. Flags can then be loaded manually. ```dart config.preloadFeatureFlags = false; // Load flags manually ``` -------------------------------- ### Reset SDK State Source: https://github.com/posthog/posthog-flutter/blob/main/_autodocs/api-reference/posthog.md Resets all cached properties and the distinct ID, effectively re-initializing the SDK. The SDK must be re-initialized with setup() after calling this. ```dart await Posthog().reset(); ``` -------------------------------- ### PosthogObserver Class Source: https://github.com/posthog/posthog-flutter/blob/main/_autodocs/types.md Navigator observer for automatic screen tracking. ```APIDOC ## PosthogObserver Class ### Description Navigator observer for automatic screen tracking. ### Constructor `PosthogObserver({ScreenNameExtractor nameExtractor = defaultNameExtractor, PostHogRouteFilter routeFilter = defaultPostHogRouteFilter})` Creates a new PosthogObserver with optional screen name extractor and route filter. ``` -------------------------------- ### PostHogWidget Widget Source: https://github.com/posthog/posthog-flutter/blob/main/_autodocs/types.md Root widget for session replay capture. ```APIDOC ## PostHogWidget Widget ### Description Root widget for session replay capture. ### Constructor `const PostHogWidget({required this.child})` Creates a PostHogWidget with a required child widget. ``` -------------------------------- ### Feature Flag Enabled Status Example Source: https://github.com/posthog/posthog-flutter/blob/main/_autodocs/api-reference/feature-flags.md Checks the enabled status of a feature flag. This can be used for both boolean and multivariate flags to determine if any variant is active. ```dart final result = await Posthog().getFeatureFlagResult('new_checkout'); if (result?.enabled ?? false) { // Show new checkout interface } ``` -------------------------------- ### Utility Methods Source: https://github.com/posthog/posthog-flutter/blob/main/_autodocs/MANIFEST.md General utility methods for the SDK. ```APIDOC ## Utility Methods ### `flush()` #### Description Flushes any pending events to the PostHog server. ### `debug(bool enabled)` #### Description Enables or disables debug logging for the SDK. ``` -------------------------------- ### Run CI-aligned local checks Source: https://github.com/posthog/posthog-flutter/blob/main/CONTRIBUTING.md Execute these commands from the repository root to perform the same checks that the Continuous Integration (CI) system uses. ```bash flutter pub get make installLinters make checkFormatDart make analyzeDart make formatKotlin make formatSwift cd posthog_flutter && flutter test ``` -------------------------------- ### Create Default Session Replay Config Source: https://github.com/posthog/posthog-flutter/blob/main/_autodocs/api-reference/posthog-config.md Creates a session replay configuration with default masking enabled. Use this to customize session replay behavior. ```dart final replayConfig = PostHogSessionReplayConfig(); replayConfig.maskAllTexts = false; ``` -------------------------------- ### Get Current Session ID Source: https://github.com/posthog/posthog-flutter/blob/main/_autodocs/api-reference/posthog.md Retrieve the unique identifier for the current user session. Returns null if no session is active or if the platform cannot provide an ID. ```dart final sessionId = await Posthog().getSessionId(); if (sessionId != null) { print('Session: $sessionId'); } ``` -------------------------------- ### Get the value of a feature flag Source: https://github.com/posthog/posthog-flutter/blob/main/_autodocs/api-reference/posthog.md Retrieves the value of a feature flag. This can be a boolean, a variant key string for multivariate flags, or null if the flag is not found. ```dart final flagValue = await Posthog().getFeatureFlag('color_theme'); if (flagValue == 'dark') { // Apply dark theme } ``` -------------------------------- ### PosthogObserver Constructor Source: https://github.com/posthog/posthog-flutter/blob/main/_autodocs/api-reference/posthog-observer.md Initializes the PosthogObserver with optional custom screen name extraction and route filtering functions. It integrates with the app's navigator to track route changes and send screen events. ```APIDOC ## PosthogObserver Constructor ### Description Initializes the PosthogObserver with optional custom screen name extraction and route filtering functions. It integrates with the app's navigator to track route changes and send screen events. ### Parameters - **nameExtractor** (ScreenNameExtractor) - Optional - Function to extract a screen name from route settings. Defaults to `defaultNameExtractor`. - **routeFilter** (PostHogRouteFilter) - Optional - Function to determine which routes should be tracked. Defaults to `defaultPostHogRouteFilter`. ### Behavior - Automatically registers itself with `WidgetsBinding` to monitor app lifecycle. - Only sends screen events when the app is in the foreground (resumed state). ### Example ```dart final observer = PosthogObserver( nameExtractor: (settings) => settings.name, routeFilter: (route) => route is PageRoute, ); MaterialApp( navigatorObservers: [observer], // ... other settings ); ``` ``` -------------------------------- ### Build and Upload Web Sourcemaps Source: https://github.com/posthog/posthog-flutter/blob/main/example/README.md Builds the web version of the Flutter app and injects/uploads sourcemaps for PostHog. Ensure release name, version, and build number are accurate. ```bash rm -rf build/web flutter build web --source-maps posthog-cli sourcemap inject --directory build/web --release-name posthog_flutter_example --release-version 1.0.0 --build 42 # check the sourcemaps has chunk_id and release_id injected (*.js.map file) # check the js file has _posthogChunkIds injected (*.js file) # check the chunk_id and _posthogChunkIds match posthog-cli sourcemap upload --directory build/web --release-name posthog_flutter_example --release-version 1.0.0 --build 42 cd build/web # https://pub.dev/packages/dhttpd dhttpd ``` -------------------------------- ### Multivariate Feature Flag Variant Example Source: https://github.com/posthog/posthog-flutter/blob/main/_autodocs/api-reference/feature-flags.md Accesses the variant of a multivariate feature flag. Use a switch statement to conditionally execute code based on the active variant. ```dart final result = await Posthog().getFeatureFlagResult('experiment_version'); switch (result?.variant) { case 'control': showControlVersion(); break; case 'treatment': showTreatmentVersion(); break; default: showDefaultVersion(); } ``` -------------------------------- ### Check Boolean Feature Flag Example Source: https://github.com/posthog/posthog-flutter/blob/main/_autodocs/api-reference/feature-flags.md Determines if a boolean feature flag is enabled. This is the most common way to check feature flag status for simple on/off scenarios. ```dart final enabled = await Posthog().isFeatureEnabled('new_ui'); if (enabled) { // Show new interface } ``` -------------------------------- ### Configure PostHog with Analytics Features Source: https://github.com/posthog/posthog-flutter/blob/main/_autodocs/configuration.md Set up the PostHog configuration with specific options for feature flags, application lifecycle events, person profiles, and error tracking. ```dart final config = PostHogConfig('phc_token'); config.preloadFeatureFlags = true; config.captureApplicationLifecycleEvents = true; config.personProfiles = PostHogPersonProfiles.always; config.errorTrackingConfig.captureFlutterErrors = true; config.errorTrackingConfig.captureNativeExceptions = true; ``` -------------------------------- ### Configure Session Replay Behavior Source: https://github.com/posthog/posthog-flutter/blob/main/_autodocs/api-reference/posthog-widget.md Customize session replay behavior using `PostHogConfig.sessionReplayConfig`. Options include masking texts/images, adjusting throttle delay for performance, and setting a sample rate. ```dart final config = PostHogConfig('your-token'); config.sessionReplay = true; // Masking config.sessionReplayConfig.maskAllTexts = true; // Default config.sessionReplayConfig.maskAllImages = true; // Default // Performance config.sessionReplayConfig.throttleDelay = Duration(milliseconds: 500); // Sampling config.sessionReplayConfig.sampleRate = 0.5; // Record 50% of sessions ``` -------------------------------- ### Convert PostHogConfig to Map Source: https://github.com/posthog/posthog-flutter/blob/main/_autodocs/api-reference/posthog-config.md Converts the PostHog configuration to a platform-channel map for native SDK initialization. This method is called internally by Posthog().setup() and does not need to be called directly. ```dart Map toMap() ``` -------------------------------- ### Disable Automatic Application Lifecycle Events Source: https://github.com/posthog/posthog-flutter/blob/main/_autodocs/api-reference/posthog-config.md Set to false to prevent the SDK from automatically capturing application lifecycle events such as app opened, backgrounded, installed, and updated. ```dart config.captureApplicationLifecycleEvents = false; ``` -------------------------------- ### PosthogObserver Constructor Source: https://github.com/posthog/posthog-flutter/blob/main/_autodocs/api-reference/posthog-observer.md Instantiate PosthogObserver with optional custom name extractors and route filters. It automatically registers with WidgetsBinding and only sends events when the app is in the foreground. ```dart PosthogObserver({ ScreenNameExtractor nameExtractor = defaultNameExtractor, PostHogRouteFilter routeFilter = defaultPostHogRouteFilter, }) ``` -------------------------------- ### Session Replay Configuration Source: https://github.com/posthog/posthog-flutter/blob/main/_autodocs/api-reference/posthog-config.md Configure session replay settings, including masking all text content and setting a throttle delay for replay events. ```APIDOC ## sessionReplayConfig Configuration object for session replay masking and throttling. ```dart PostHogSessionReplayConfig sessionReplayConfig = PostHogSessionReplayConfig() ``` ### Related Type See `PostHogSessionReplayConfig` for available masking and performance options. ### Example ```dart config.sessionReplayConfig.maskAllTexts = true; config.sessionReplayConfig.throttleDelay = Duration(milliseconds: 500); ``` ``` -------------------------------- ### Custom Route Filter Source: https://github.com/posthog/posthog-flutter/blob/main/_autodocs/types.md Implement a custom route filter to control which routes are tracked as screen views. This example skips tracking fullscreen dialogs. It is used in the PosthogObserver constructor. ```dart PostHogRouteFilter customFilter = (route) { if (route is PageRoute) { return !route.fullscreenDialog; // Skip dialogs } return false; }; PosthogObserver(routeFilter: customFilter); ``` -------------------------------- ### PostHogConfig Constructor Source: https://github.com/posthog/posthog-flutter/blob/main/_autodocs/api-reference/posthog-config.md Initializes the PostHogConfig object with a project token and optional callbacks for feature flags and event modification. ```APIDOC ## PostHogConfig Constructor ### Description Initializes the PostHogConfig object with a project token and optional callbacks for feature flags and event modification. ### Parameters #### Path Parameters - **projectToken** (String) - Required - Your PostHog project token (trimmed before storage) - **onFeatureFlags** (OnFeatureFlagsCallback?) - Optional - Callback invoked when feature flags finish loading - **beforeSend** (List?) - Optional - List of callbacks to modify or drop events before sending ### Example ```dart final config = PostHogConfig('phc_your_token'); config.host = 'https://your-posthog-instance.com'; config.sessionReplay = true; await Posthog().setup(config); ``` ``` -------------------------------- ### Get Full Flag Result Source: https://github.com/posthog/posthog-flutter/blob/main/_autodocs/api-reference/feature-flags.md Retrieves the full result of a feature flag, including its enabled status, variant, and payload. This is the primary method for accessing feature flag configurations. ```APIDOC ## getFeatureFlagResult ### Description Retrieves the full result of a feature flag, including its enabled status, variant, and payload. This is the primary method for accessing feature flag configurations. ### Method `getFeatureFlagResult(String key, {bool sendEvent = true})` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```dart final result = await Posthog().getFeatureFlagResult('color_scheme'); if (result != null) { if (result.enabled) { // Use the result if (result.variant == 'dark') { applyDarkTheme(); } else if (result.variant == 'light') { applyLightTheme(); } } // Access payload if available if (result.payload is Map) { final config = result.payload as Map; // Use configuration from payload } } ``` ### Response #### Success Response - **enabled** (bool) - Whether the feature flag is enabled. - **variant** (string) - The variant of the feature flag. - **payload** (dynamic) - The payload associated with the feature flag. #### Response Example ```json { "enabled": true, "variant": "dark", "payload": { "setting1": "value1" } } ``` ``` -------------------------------- ### Optimize Session Replay Performance Source: https://github.com/posthog/posthog-flutter/blob/main/_autodocs/api-reference/posthog-widget.md Adjust the `throttleDelay` in `PostHogConfig.sessionReplayConfig` to balance snapshot frequency and performance. Lower values increase fidelity but impact resources; higher values improve performance at the cost of fidelity. ```dart // For performance-critical scenarios config.sessionReplayConfig.throttleDelay = Duration(seconds: 2); // For high-fidelity replays config.sessionReplayConfig.throttleDelay = Duration(milliseconds: 250); ``` -------------------------------- ### Get Full Feature Flag Result Source: https://github.com/posthog/posthog-flutter/blob/main/_autodocs/api-reference/feature-flags.md Retrieves the complete result of a feature flag, including its enabled status, variant, and payload. Access the payload if it's a Map for configuration details. ```dart final result = await Posthog().getFeatureFlagResult('color_scheme'); if (result != null) { if (result.enabled) { // Use the result if (result.variant == 'dark') { applyDarkTheme(); } else if (result.variant == 'light') { applyLightTheme(); } } // Access payload if available if (result.payload is Map) { final config = result.payload as Map; // Use configuration from payload } } ``` -------------------------------- ### Lifecycle Methods Source: https://github.com/posthog/posthog-flutter/blob/main/_autodocs/api-reference/posthog-observer.md Details the `NavigatorObserver` lifecycle methods (`didPush`, `didReplace`, `didPop`) that the `PosthogObserver` utilizes to capture screen events upon route changes. It also includes `didChangeAppLifecycleState` for managing events based on app state. ```APIDOC ## Lifecycle Methods ### Description The observer automatically integrates with Flutter's navigation system and app lifecycle to capture screen events. ### `didPush` #### Description Captures a screen event when a route is pushed onto the navigator stack. #### Signature ```dart void didPush(Route route, Route? previousRoute) ``` ### `didReplace` #### Description Captures a screen event when a route is replaced. #### Signature ```dart void didReplace({Route? newRoute, Route? oldRoute}) ``` ### `didPop` #### Description Captures a screen event for the previous route when a route is popped. #### Signature ```dart void didPop(Route route, Route? previousRoute) ``` ### `didChangeAppLifecycleState` #### Description Tracks app lifecycle state to suppress screen events when the app is backgrounded. #### Signature ```dart void didChangeAppLifecycleState(AppLifecycleState state) ``` ``` -------------------------------- ### Access PostHog Singleton Source: https://github.com/posthog/posthog-flutter/blob/main/_autodocs/README.md Access the SDK through the Posthog() singleton to capture events or identify users. ```dart Posthog().capture(eventName: 'user_action'); Posthog().identify(userId: 'user@example.com'); ```