Search code examples
flutterdarterror-loggingposthog

How to change the PostHog project at runtime in Flutter?


I'm planning to integrate PostHog into my Flutter program. After the user logs in to my app, I want to modify the PostHog project.

Add your PostHog configuration to the AndroidManifest.xml file:

<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="your.package.name">
  <application>
    <meta-data android:name="com.posthog.posthog.API_KEY" android:value="YOUR_API_KEY" />
    <meta-data android:name="com.posthog.posthog.POSTHOG_HOST" android:value="https://app.posthog.com" />
    <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>

Update the minimum Android SDK version to 21 in android/app/build.gradle:

defaultConfig {
  minSdkVersion 21
}

main.dart file:

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) {
    return MaterialApp(
      title: 'Flutter Analytics',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: HomePage(),
    );
  }
}

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Home'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            Posthog().capture(event: 'button_clicked');
          },
          child: Text('Click me'),
        ),
      ),
    );
  }
}

How can I use Flutter to make runtime changes to the PostHog project?


Solution

  • Attaching user to analytic events

    If by change you mean attaching events to the logged in user, you can use the identify() method:

    await Posthog().identify(
       userId: userId,
       userProperties: { // optional
         'email': email,
         'role': role,
       },
    )
    

    After this, all tracked events will automatically be attached to your logged in user, based on their userId. If you want to logout user then make sure to call reset() so you can identify the next logged in user.

    await Posthog().reset();
    

    Changing Posthog Config Dynamically

    However, if by change you meant to change the Posthog config dynamically you need to go the manual route for initialization.

    1. Remove what you currently have for posthog in the AndroidManifest.xml and instead add this line:
    <meta-data android:name="com.posthog.posthog.AUTO_INIT" android:value="false" />
    
    1. Add the following posthog initialization code in your main.dart:
    WidgetsBinding.ensureInitialized(); // add this code before posthog init
    
    final config = PostHogConfig('<YOUR_POSTHOG_API_KEY>')
      ..debug = true
      ..captureApplicationLifecycleEvents = true
      ..host = '<YOUR_POSTHOG_HOST>';
    await Posthog().setup(config);
    
    1. Now you're posthog config exists in Flutter code and you can apply your logic for changing whatever properties you want to change about Posthog config.