Skip to content

Commit

Permalink
fix: allow tracking on PageRoute screens using the PosthogObserver as…
Browse files Browse the repository at this point in the history
… well
  • Loading branch information
marandaneto committed Apr 2, 2024
1 parent f5b8658 commit 62f25b1
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 13 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
## Next

- Allow tracking non `PageRoute` screens using the `PosthogObserver` ([#108](

## 4.3.0

- add PrivacyInfo ([#94](https://github.com/PostHog/posthog-flutter/pull/94))
Expand Down
31 changes: 18 additions & 13 deletions lib/src/posthog_observer.dart
Original file line number Diff line number Diff line change
Expand Up @@ -12,39 +12,44 @@ class PosthogObserver extends RouteObserver<PageRoute<dynamic>> {

final ScreenNameExtractor _nameExtractor;

void _sendScreenView(PageRoute<dynamic> route) {
String? screenName = _nameExtractor(route.settings);
if (screenName != null) {
bool _isTrackeableRoute(String? name) {
return name != null && name.trim().isNotEmpty;
}

void _sendScreenView(Route<dynamic>? route) {
if (route == null) {
return;
}

var screenName = _nameExtractor(route.settings);
if (_isTrackeableRoute(screenName)) {
// if the screen name is the root route, we send it as root ("/") instead of only "/"
if (screenName == '/') {
screenName = 'root (\'/\')';
}

Posthog().screen(screenName: screenName);
Posthog().screen(screenName: screenName!);
}
}

@override
void didPush(Route<dynamic> route, Route<dynamic>? previousRoute) {
super.didPush(route, previousRoute);
if (route is PageRoute) {
_sendScreenView(route);
}

_sendScreenView(route);
}

@override
void didReplace({Route<dynamic>? newRoute, Route<dynamic>? oldRoute}) {
super.didReplace(newRoute: newRoute, oldRoute: oldRoute);
if (newRoute is PageRoute) {
_sendScreenView(newRoute);
}

_sendScreenView(newRoute);
}

@override
void didPop(Route<dynamic> route, Route<dynamic>? previousRoute) {
super.didPop(route, previousRoute);
if (previousRoute is PageRoute && route is PageRoute) {
_sendScreenView(previousRoute);
}

_sendScreenView(previousRoute);
}
}

0 comments on commit 62f25b1

Please sign in to comment.