customerio / customerio-flutter

Flutter plugin for Customer.io
https://www.customer.io/docs/sdk/flutter/getting-started/
MIT License
12 stars 10 forks source link

Improve Screen Tracking by Implementing NavigatorObserver-Based CustomerIORouteObserver #87

Open AristideVB opened 1 year ago

AristideVB commented 1 year ago

Problem

The current approach to screen/route tracking relies on manual listener attachment for each route change in our app. The existing strategy is non-idiomatic for Flutter and potentially less efficient:

_router.addListener(() => _onRouteChanged());

void _onRouteChanged() {
  if (_customerIOSDK.sdkConfig?.screenTrackingEnabled == true) {
    final Screen? screen = _router.location.toAppScreen();
    if (screen != null) {
      CustomerIO.screen(name: screen.name);
    }
  }
}

Proposed Solution

To solve this, I propose implementing CustomerIORouteObserver that leverages Flutter's NavigatorObserver. This approach aligns better with Flutter best practices and allows for more efficient and reliable route tracking. The GoRouter package supports route observers, allowing this new class to integrate seamlessly.

Integration with GoRouter

GoRouter provides a way to attach observers to your routes, enabling cleaner and more idiomatic tracking of screen views. You can easily add the CustomerIORouteObserver to the GoRouter setup like this:

GoRouter(
  observers: [CustomerIORouteObserver()],
  // ... other configurations
)

By adding the observer directly into GoRouter's observers array, we can automatically and efficiently handle route tracking without requiring any manual intervention for each route change.

Integration with MaterialApp

MaterialApp(
  home: MyAppHome(),
  navigatorObservers: [
    CustomerIORouteObserver(),
  ],
)

With this new setup, every time a route change occurs, the CustomerIORouteObserver will automatically fire and send the necessary tracking information to CustomerIO.

WellDunDun commented 1 year ago

Great suggestions and I really hope they implement them! I've been really struggling to get screen tracking working with GoRouter and I'm in desperate need of some help.

aqrc commented 1 year ago

There is such code for observer in official documentation which can be copy-pasted https://customer.io/docs/sdk/flutter/track-events/#auto-screenview

I agree though that it would be nice to have it out of the box)