-
Notifications
You must be signed in to change notification settings - Fork 207
feat: analytics auto-tracking helpers for Web and Flutter #1622
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
lohanidamodar
wants to merge
5
commits into
main
Choose a base branch
from
feat/analytics-auto-tracking
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
b72475d
feat(web): add analytics auto-tracking helpers
lohanidamodar 2ea313c
feat(flutter): add AnalyticsObserver and lifecycle tracking helpers
lohanidamodar 722e2ad
refactor(analytics): normalize auto-emitted event names to snake_case
lohanidamodar 5a5939e
fix(analytics): stop engagement timer on pagehide; init Flutter bindi…
lohanidamodar 0b5c5af
feat(analytics): report engagement time incrementally as per-flush de…
lohanidamodar File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,140 @@ | ||
| import 'package:flutter/widgets.dart'; | ||
|
|
||
| /// Signature used to emit an analytics event from an [AnalyticsObserver] or | ||
| /// [AnalyticsTracking] instance. | ||
| /// | ||
| /// The generated `Analytics` service exposes `event({required String name, ...})`, | ||
| /// so the typical wiring is: | ||
| /// | ||
| /// ```dart | ||
| /// final analytics = Analytics(client); | ||
| /// final observer = AnalyticsObserver( | ||
| /// (name, {props, propertyId, engagementTime}) => analytics.event( | ||
| /// name: name, | ||
| /// props: props, | ||
| /// propertyId: propertyId, | ||
| /// engagementTime: engagementTime, | ||
| /// ), | ||
| /// propertyId: '<PROPERTY_ID>', | ||
| /// ); | ||
| /// ``` | ||
| /// | ||
| /// [propertyId] and [engagementTime] map to the endpoint's top-level params of | ||
| /// the same name; both are null unless the helper has something to say about | ||
| /// them, so a closure is free to ignore either. | ||
| typedef AnalyticsEventEmitter = void Function( | ||
| String name, { | ||
| Map<String, dynamic>? props, | ||
| String? propertyId, | ||
| int? engagementTime, | ||
| }); | ||
|
|
||
| /// Signature used to derive a screen name from a [Route]. | ||
| /// | ||
| /// Return `null` to skip tracking the route entirely (for example, dialogs or | ||
| /// bottom sheets that shouldn't count as screen views). | ||
| typedef ScreenNameExtractor = String? Function(Route<dynamic> route); | ||
|
|
||
| /// Default [ScreenNameExtractor] — uses [RouteSettings.name] when present and | ||
| /// falls back to `null` (route is skipped) otherwise. Anonymous routes are | ||
| /// generally noise for analytics, so opting out by default keeps dashboards | ||
| /// clean. | ||
| String? defaultScreenNameExtractor(Route<dynamic> route) { | ||
| return route.settings.name; | ||
| } | ||
|
|
||
| /// [NavigatorObserver] that fires an analytics event every time a named route | ||
| /// is pushed, popped-back-to, replaced or removed. | ||
| /// | ||
| /// Attach to a `MaterialApp` (or `CupertinoApp`, `WidgetsApp`) via | ||
| /// `navigatorObservers`: | ||
| /// | ||
| /// ```dart | ||
| /// MaterialApp( | ||
| /// navigatorObservers: [ | ||
| /// AnalyticsObserver( | ||
| /// (name, {props, propertyId, engagementTime}) => analytics.event( | ||
| /// name: name, | ||
| /// props: props, | ||
| /// propertyId: propertyId, | ||
| /// engagementTime: engagementTime, | ||
| /// ), | ||
| /// propertyId: '<PROPERTY_ID>', | ||
| /// ), | ||
| /// ], | ||
| /// ... | ||
| /// ); | ||
| /// ``` | ||
| class AnalyticsObserver extends NavigatorObserver { | ||
| /// Callback used to send the resulting `screen_view` event. | ||
| final AnalyticsEventEmitter emit; | ||
|
|
||
| /// Optional route-name extractor. Defaults to [defaultScreenNameExtractor] | ||
| /// which reads [RouteSettings.name]. | ||
| final ScreenNameExtractor nameExtractor; | ||
|
|
||
| /// Event name used for screen views. Defaults to `screen_view`. | ||
| final String eventName; | ||
|
|
||
| /// Analytics property (or snippet) ID forwarded with every emitted event. | ||
| /// Optional — leave null when the emitter closure already supplies one. | ||
| final String? propertyId; | ||
|
|
||
| AnalyticsObserver( | ||
| this.emit, { | ||
| ScreenNameExtractor? nameExtractor, | ||
| this.eventName = 'screen_view', | ||
| this.propertyId, | ||
| }) : nameExtractor = nameExtractor ?? defaultScreenNameExtractor; | ||
|
|
||
| @override | ||
| void didPush(Route<dynamic> route, Route<dynamic>? previousRoute) { | ||
| _sendScreenView(route, previousRoute, trigger: 'push'); | ||
| } | ||
|
|
||
| @override | ||
| void didReplace({Route<dynamic>? newRoute, Route<dynamic>? oldRoute}) { | ||
| if (newRoute != null) { | ||
| _sendScreenView(newRoute, oldRoute, trigger: 'replace'); | ||
| } | ||
| } | ||
|
|
||
| @override | ||
| void didPop(Route<dynamic> route, Route<dynamic>? previousRoute) { | ||
| if (previousRoute != null) { | ||
| _sendScreenView(previousRoute, route, trigger: 'pop'); | ||
| } | ||
| } | ||
|
|
||
| @override | ||
| void didRemove(Route<dynamic> route, Route<dynamic>? previousRoute) { | ||
| if (previousRoute != null) { | ||
| _sendScreenView(previousRoute, route, trigger: 'remove'); | ||
| } | ||
| } | ||
|
|
||
| void _sendScreenView( | ||
| Route<dynamic> route, | ||
| Route<dynamic>? previousRoute, { | ||
| required String trigger, | ||
| }) { | ||
| final name = nameExtractor(route); | ||
| if (name == null || name.isEmpty) { | ||
| return; | ||
| } | ||
| final props = <String, dynamic>{ | ||
| 'screen': name, | ||
| 'trigger': trigger, | ||
| }; | ||
| final previousName = previousRoute == null ? null : nameExtractor(previousRoute); | ||
| if (previousName != null && previousName.isNotEmpty) { | ||
| props['previous'] = previousName; | ||
| } | ||
| try { | ||
| emit(eventName, props: props, propertyId: propertyId); | ||
| } catch (_) { | ||
| // Emitter failures must never propagate into the navigator stack — | ||
| // swallow so analytics can't crash the app. | ||
| } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,181 @@ | ||
| import 'package:flutter/widgets.dart'; | ||
|
|
||
| import 'analytics_observer.dart'; | ||
|
|
||
| export 'analytics_observer.dart' show AnalyticsEventEmitter, AnalyticsObserver, ScreenNameExtractor; | ||
|
|
||
| /// Companion class for the generated `Analytics` service that wires up the | ||
| /// mobile-idiomatic auto-tracking primitives: app-lifecycle events (backgrounded | ||
| /// / foregrounded) and manual `screenView` calls. | ||
| /// | ||
| /// Auto-emitted event names follow `snake_case` + lowercase (`pageview`, | ||
| /// `screen_view`, `app_backgrounded`, `app_foregrounded`, etc.). Prop keys use | ||
| /// camelCase to match the endpoint's parameter naming. | ||
| /// | ||
| /// Attach an [AnalyticsObserver] to your `MaterialApp` for automatic route | ||
| /// tracking; use [AnalyticsTracking] on top for lifecycle events and the | ||
| /// convenience `screenView` / `event` shortcuts. | ||
| /// | ||
| /// [enableAutoLifecycleEvents] calls [WidgetsFlutterBinding.ensureInitialized] | ||
| /// internally, so it is safe to invoke before [runApp] without wiring up the | ||
| /// binding manually. Callers who need the binding for their own initialization | ||
| /// (async setup, plugin channels, etc.) can still call `ensureInitialized()` | ||
| /// themselves — the call is idempotent. | ||
| /// | ||
| /// Engagement time is reported the same way the Web helper reports it: as a | ||
| /// **delta** attached to each `app_backgrounded` event, covering only the | ||
| /// foreground time accrued since the last resume. Backgrounding is the mobile | ||
| /// equivalent of a browser tab going hidden, and it is where the Web helper | ||
| /// flushes too, so the two platforms feed the same additive `engagementTime` | ||
| /// column. The seconds ride on the lifecycle event that is already being sent | ||
| /// at that exact moment rather than adding a second request for a single | ||
| /// number. | ||
| /// | ||
| /// Typical wiring: | ||
| /// | ||
| /// ```dart | ||
| /// final analytics = Analytics(client); | ||
| /// final emit = (String name, {Map<String, dynamic>? props, String? propertyId, int? engagementTime}) => | ||
| /// analytics.event( | ||
| /// name: name, | ||
| /// props: props, | ||
| /// propertyId: propertyId, | ||
| /// engagementTime: engagementTime, | ||
| /// ); | ||
| /// | ||
| /// final tracking = AnalyticsTracking(emit, propertyId: '<PROPERTY_ID>'); | ||
| /// tracking.enableAllAutoTracking(); | ||
| /// | ||
| /// runApp(MaterialApp( | ||
| /// navigatorObservers: [ | ||
| /// AnalyticsObserver(emit, propertyId: '<PROPERTY_ID>'), | ||
| /// ], | ||
| /// home: MyApp(), | ||
| /// )); | ||
| /// ``` | ||
| class AnalyticsTracking with WidgetsBindingObserver { | ||
| final AnalyticsEventEmitter _emit; | ||
|
|
||
| /// Analytics property (or snippet) ID forwarded with every emitted event. | ||
| /// Optional — leave null when the emitter closure already supplies one. | ||
| final String? propertyId; | ||
|
|
||
| bool _lifecycleAttached = false; | ||
| DateTime? _foregroundSince; | ||
|
|
||
| /// Sub-second engagement left over from the previous flush. Carried forward | ||
| /// so a session made of many short foreground stretches does not lose a | ||
| /// fraction of a second to truncation on every one of them. | ||
| Duration _engagementCarry = Duration.zero; | ||
|
|
||
| AnalyticsTracking(AnalyticsEventEmitter emit, {this.propertyId}) : _emit = emit; | ||
|
|
||
| /// Enable the opinionated default auto-tracking set. Currently this covers | ||
| /// lifecycle events; route tracking is opt-in via [AnalyticsObserver]. | ||
| void enableAllAutoTracking() { | ||
| enableAutoLifecycleEvents(); | ||
| } | ||
|
|
||
| /// Start emitting `app_backgrounded` and `app_foregrounded` events when the | ||
| /// host app changes lifecycle state. Idempotent — repeat calls no-op. | ||
| /// | ||
| /// Calls [WidgetsFlutterBinding.ensureInitialized] internally so this is | ||
| /// safe to invoke before [runApp] without the caller having to bootstrap | ||
| /// the binding themselves. | ||
| void enableAutoLifecycleEvents() { | ||
| if (_lifecycleAttached) { | ||
| return; | ||
| } | ||
| // WidgetsBinding.instance throws StateError if the binding has not been | ||
| // set up yet. The docstring example wires this call before runApp(), so | ||
| // ensure the binding here — the call is idempotent. | ||
| WidgetsFlutterBinding.ensureInitialized(); | ||
| _lifecycleAttached = true; | ||
| _foregroundSince = DateTime.now(); | ||
| _engagementCarry = Duration.zero; | ||
| WidgetsBinding.instance.addObserver(this); | ||
| } | ||
|
|
||
| /// Stop emitting lifecycle events. Safe to call when auto-lifecycle was | ||
| /// never enabled. | ||
| void disableAutoLifecycleEvents() { | ||
| if (!_lifecycleAttached) { | ||
| return; | ||
| } | ||
| _lifecycleAttached = false; | ||
| _foregroundSince = null; | ||
| _engagementCarry = Duration.zero; | ||
| WidgetsBinding.instance.removeObserver(this); | ||
| } | ||
|
|
||
| /// Emit an ad-hoc analytics event. Emitter exceptions are swallowed so | ||
| /// analytics failures never surface to the host app. | ||
| void event( | ||
| String name, { | ||
| Map<String, dynamic>? props, | ||
| int? engagementTime, | ||
| }) { | ||
| try { | ||
| _emit( | ||
| name, | ||
| props: props, | ||
| propertyId: propertyId, | ||
| engagementTime: engagementTime, | ||
| ); | ||
| } catch (_) { | ||
| // Silent — see class docs. | ||
| } | ||
| } | ||
|
|
||
| /// Mobile-idiomatic screen-view shortcut. Renders as a `screen_view` | ||
| /// analytics event with `screen`, optional `screenClass` and any | ||
| /// caller-supplied properties. | ||
| void screenView( | ||
| String name, { | ||
| String? className, | ||
| Map<String, dynamic>? props, | ||
| }) { | ||
| final merged = <String, dynamic>{'screen': name}; | ||
| if (className != null) { | ||
| merged['screenClass'] = className; | ||
| } | ||
| if (props != null) { | ||
| merged.addAll(props); | ||
| } | ||
| event('screen_view', props: merged); | ||
| } | ||
|
|
||
| @override | ||
| void didChangeAppLifecycleState(AppLifecycleState state) { | ||
| switch (state) { | ||
| case AppLifecycleState.paused: | ||
| case AppLifecycleState.hidden: | ||
| // On Flutter desktop and web the lifecycle transitions through both | ||
| // `hidden` and `paused` when the window is minimised / closed. Guard | ||
| // on `_foregroundSince` so we emit `app_backgrounded` exactly once | ||
| // per background transition instead of firing a second empty event — | ||
| // which is also what keeps the engagement delta from being billed | ||
| // twice for one transition. | ||
| final since = _foregroundSince; | ||
| if (since == null) { | ||
| break; | ||
| } | ||
| _foregroundSince = null; | ||
| final elapsed = _engagementCarry + DateTime.now().difference(since); | ||
| final seconds = elapsed.inSeconds; | ||
| _engagementCarry = elapsed - Duration(seconds: seconds); | ||
| event( | ||
| 'app_backgrounded', | ||
| engagementTime: seconds > 0 ? seconds : null, | ||
| ); | ||
| break; | ||
|
greptile-apps[bot] marked this conversation as resolved.
|
||
| case AppLifecycleState.resumed: | ||
| _foregroundSince = DateTime.now(); | ||
| event('app_foregrounded'); | ||
| break; | ||
| case AppLifecycleState.inactive: | ||
| case AppLifecycleState.detached: | ||
| break; | ||
| } | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.