DEV Community

Abdur Rafay Saleem
Abdur Rafay Saleem

Posted on

Implementing Posthog Analytics in Flutter Tutorial

Previous Article: Part 2: Implementing Logger and Server Analytics

PostHog is a powerful open-source analytics platform that provides comprehensive user behavior tracking. In this article, we'll implement PostHog analytics in Flutter using our analytics architecture.

PostHog Setup

You need to follow the following series of steps in order to prepare posthog for flutter.

1. PostHog account creation

Visit Posthog Website and signup to create your account using either email, google, or github etc.

2. Project setup

Once you open you new account, you will see a default project already opened.

  • Click the dropdown arrow next to its name > Click the gear icon to open settings.
  • Set a custom name for your project.
  • Scroll down and copy the API_KEY value
  • Also note the if the region is US or EU

Posthog API KEY

3. Flutter package setup + configuration

  1. Add the package posthog_flutter to your pubspec.yaml.
  2. Add the following line to your AndroidManifest.xml inside <application> tags
<application>
....
    <meta-data android:name="com.posthog.posthog.AUTO_INIT" android:value="false" />
</application>
Enter fullscreen mode Exit fullscreen mode

The reason we are disabling AUTO_INIT is because we will provide the config inside flutter code. That allows us to apply dynamic logic for flavors.

  1. Do the same for ios inside Info.plist file:
<dict>
    ....
    <key>com.posthog.posthog.AUTO_INIT</key>
    <false/>
</dict>
Enter fullscreen mode Exit fullscreen mode
  1. In main.dart or whatever your entry file is, add the following code:
import 'package:posthog_flutter/posthog_flutter.dart';
....
Future<void> main() async {
  WidgetsBinding.ensureInitialized();
  final config = PostHogConfig(`<YOUR_API_KEY>`)
    ..debug = true
    ..captureApplicationLifecycleEvents = true // Allows tracking backgrounded, foregrounded etc. events
    ..host = 'https://us.i.posthog.com'; // or for EU Region 'https://eu.i.posthog.com'
  await Posthog().setup(config);

  runApp();
}
Enter fullscreen mode Exit fullscreen mode

PostHog Analytics Implementation

Our PosthogAnalyticsClient implements the AnalyticsClientBase contract while utilizing PostHog's specific APIs:

Key Features

  • User identification
  • Event tracking
  • Screen tracking
  • Custom properties
  • User properties
  • Session management

Attaching user to analytic events

When you originally track events, they are done so anonymously. Posthog provides methods to attach events to users and maintain nice sessions. To attach events to logged in user, you can use the identify() method:

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

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();
Enter fullscreen mode Exit fullscreen mode

Tracking Screen Views

If you want to track screen changes use:

_posthog.screen(
  screenName: routeName,
  properties: {'action': action},
)
Enter fullscreen mode Exit fullscreen mode

Custom Events

Or for custom events use:

_posthog.capture(
  eventName: 'button_pressed',
  properties: {
    'button_name': buttonName,
    ...?data,
  },
);
Enter fullscreen mode Exit fullscreen mode

Implementation Notes

  • Using posthog this way allows maximum flexibility and a nice wrapper around the original methods.

Coming Up Next

In Part 4: Creating a Unified Analytics Service Facade, we'll bring everything together with a facade service that manages multiple analytics clients seamlessly.

Top comments (0)