event_tracker_handler 0.3.1
event_tracker_handler: ^0.3.1 copied to clipboard
Multi-provider event tracking with Firebase Analytics, Mixpanel, and webhooks.
event_tracker_handler #
Multi-provider event tracking with Firebase Analytics, Mixpanel, and custom webhooks.
Features #
- Track predefined events with a single handler.
- Firebase Analytics, Mixpanel, and custom webhook backends.
- Typed user and event data (items, value, currency, custom fields).
- Timed event manager with lifecycle-aware flushing.
- Delivery outcomes per tracker plus identity merge support.
- Explicitly bootstrapped Meta App Events and consent-gated Meta Pixel on web.
Getting started #
Add event_tracker_handler to your pubspec.yaml and complete the setup for any
providers you plan to use (Firebase/Mixpanel).
If you plan to use Mixpanel on Flutter web, load the Mixpanel script from the
plugin assets in web/index.html before the Flutter app initializes:
<!-- web/index.html -->
<script src="/assets/packages/mixpanel_flutter/assets/mixpanel.js"></script>
Usage #
Create settings for each tracker and build a handler instance:
import 'package:decimal/decimal.dart';
import 'package:event_tracker_handler/event_tracker_handler.dart';
final handler = EventTrackerHandler.instance([
EventTrackerSettingsFirebase(
eventsToTrack: [EventTrackerEvents.openApp, EventTrackerEvents.purchase],
),
EventTrackerSettingsMixpanel(
token: 'YOUR_MIXPANEL_TOKEN',
eventsToTrack: [EventTrackerEvents.openApp, EventTrackerEvents.purchase],
),
EventTrackerSettingsCustomWebhook(
url: 'https://example.com/events',
eventsToTrack: [EventTrackerEvents.openApp],
),
]);
Future<void> trackPurchase() async {
await handler.init();
handler.logEvent(
type: EventTrackerEvents.purchase,
userData: EventTrackerUserData(
uuid: 'user-123',
email: 'user@example.com',
isAnonymous: false,
),
data: EventTrackerData(
value: Decimal.parse('29.90'),
currency: 'USD',
customData: {'plan': 'pro'},
),
);
}
Log events return delivery outcomes per tracker:
final outcomes = await handler.logEvent(
type: EventTrackerEvents.openApp,
userData: EventTrackerUserData(
uuid: 'user-123',
email: 'user@example.com',
isAnonymous: false,
),
);
final failed = outcomes.where((outcome) => outcome.isFailure);
You can also build tracker settings from a map:
final settings = EventTrackerSettingsModel.fromMap({
'type': 'EventTrackerType.mixpanel',
'token': 'YOUR_MIXPANEL_TOKEN',
'events': ['EventTrackerEvents.openApp', 'EventTrackerEvents.purchase'],
// Or set track_all: true to track every EventTrackerEvents value.
});
Timed events #
Use the timed event manager to start, finish, or flush active timers:
final timedManager = EventTrackerTimedEventManager(
handler: handler,
userDataProvider: () async => EventTrackerUserData(
uuid: 'user-123',
email: 'user@example.com',
isAnonymous: false,
),
);
final handle = timedManager.start(type: EventTrackerEvents.viewContent);
await timedManager.finish(handle);
Attach a lifecycle observer to flush when the app goes inactive:
final observer = EventTrackerLifecycleObserver(
timedEventManager: timedManager,
);
WidgetsBinding.instance.addObserver(observer);
Identity merge #
Merge identities when a user logs in or links accounts:
await handler.mergeIdentity(
previousUserId: 'anon-456',
userData: EventTrackerUserData(
uuid: 'user-123',
email: 'user@example.com',
isAnonymous: false,
),
);
Meta App Events #
The Meta adapter registers an inert method channel. Resolve the owning tenant's
configuration first, and call bootstrap only after the host's tenant and
platform binding checks. On iOS, Meta App Events require ATT authorization;
advertiser ID collection additionally requires the explicit collection setting.
Automatic metadata collection stays disabled until title, URL and event
envelope auditing proves it safe for the tenant's routes. The native process
binds to one tenant and App ID. A tenant or
App ID change requires a process restart; disabling Meta only blocks further
events. The client token is an SDK configuration value, not an App Secret or
Ads access token.
On Android, requestTrackingAuthorization checks the app's AD_ID permission
and whether Google Play services supplies a usable advertising ID; it does not
show a permission prompt. Missing, limited, or zeroed IDs keep advertiser ID
collection off while ordinary Meta events remain available.
The Android adapter uses Meta SDK 19.0.1. The iOS adapter uses CocoaPods
FBSDKCoreKit 19.0.0 and requires a deployment target of 15.0 or later.
The iOS host must set FacebookAutoInitEnabled,
FacebookAutoLogAppEventsEnabled, FacebookAdvertiserIDCollectionEnabled,
FacebookSKAdNetworkReportEnabled, FBSDKAutoLogMetaDataEnabled, and
FBSDKAutoLogProductImprovementEnabled to false in Info.plist. These native
defaults keep collection off before tenant resolution and SDK initialization;
the plugin configures the SDK only after bootstrap. Do not put the tenant's Meta
App ID or client token in Info.plist.
The iOS host also supplies NSUserTrackingUsageDescription for the ATT prompt.
The following native-host example runs after tenant and platform verification:
import 'package:flutter/foundation.dart';
import 'package:event_tracker_handler/event_tracker_handler.dart';
Future<bool> initializeNativeMeta() async {
final meta = MetaAppEvents.instance;
final authorized = await meta.requestTrackingAuthorization();
if (defaultTargetPlatform == TargetPlatform.iOS && !authorized) return false;
return meta.bootstrap(MetaAppEventsConfig(
tenantId: 'tenant-id',
appId: '1234567890',
clientToken: 'meta-client-token',
enabled: true,
viewContentEnabled: true,
completeRegistrationEnabled: true,
advertiserIdCollectionEnabled: authorized,
));
}
// In the public-detail visibility handler, after initialization succeeds:
Future<bool> onPublicProfileVisible(String profileId) =>
MetaAppEvents.instance.viewContent(contentId: profileId, contentType: 'profile');
// In the OTP handler, only after publishing the authenticated session:
Future<bool> onOtpSessionPublished(String challengeId) =>
MetaAppEvents.instance.completeRegistration(challengeId: challengeId);
Native App Install is produced by the SDK after activation; do not send a custom installation event. The SDK owns successful-install registration deduplication. A successful bootstrap or local request does not prove receipt or campaign attribution in Meta.
Only ViewContent for profile or event content and app-only
CompleteRegistration are exposed. The OTP challenge ID is used only for
in-process deduplication and is never sent to Meta. On web, Pixel is initialized
only when a pixel ID and explicit tenant consent are supplied in the bootstrap
config; only ViewContent is sent. Automatic configuration and Pixel SPA history
tracking are disabled before initialization. The adapter checks sensitive URL,
query, fragment and referrer contexts before loading or submitting content.
The web host must also set a no-referrer policy to avoid sending its page URL
in external HTTP referrers.
Revocation blocks later calls and reloads the document. A Pixel or tenant switch also blocks the current call and reloads before another Pixel can be used, because a loaded third-party script remains in the current document context. Persist consent per tenant in the host, clear it before disabling, and rebuild the new document's configuration from that tenant's current consent.
Additional information #
Custom webhook events include an envelope with type, timestamp, context,
and payload. The context includes app, device, user, and web metadata when
available, while the payload carries event properties and timing details.