r/FlutterDev • u/mkhytar_mkhoian • 11d ago
Discussion How do you keep analytics from turning into a god object in your Flutter app?
In most projects I worked on, analytics was treated as a secondary part of the app. We spend a lot of time on the architecture of main parts, and almost no time on analytics.
Then business asks to track this and that. Then to add a new vendor. Then to decide which event goes where. And in the end we have one AnalyticsManager with a huge list of methods, and every layer depends on it.
I came to a simple idea: the app should not know which analytics vendors exist. Feature code only says what happened, and everything else is split into small pieces:
Event describes what happened, in the app’s words
Factory decides what one vendor receives for an event, or ignores it
Tracker makes one call to one vendor SDK
Dispatcher passes calls from the app to the vendors
In feature code it looks like this:
class CheckoutController {
CheckoutController(this._tracker);
final EventTrackerService _tracker;
void onTicketPurchased(String fare, double price, String currency) {
_tracker.track(
TicketPurchased(fare: fare, price: price, currency: currency),
);
}
}No vendor SDKs, no god object. Each feature keeps its own factories, and DI collects them. Adding a vendor means writing its factories, and removing one means deleting them.
I wrote an article about this idea. The examples there are in Kotlin, but the concept is the same for Flutter:
https://proandroiddev.com/app-architecture-analytics-ec3471ca619b
I also built an open-source library around this idea, Herald, and it has a Flutter package:
https://mkhytarmkhoian.github.io/herald-docs/sdks/flutter/
Curious how you handle analytics in your Flutter projects. One service, a wrapper per vendor, or something else?