What is the best location for manually logging a screen view in Flutter with an analytics package (in my case I am using Firebase Analytics, eg. track screens)?
Looking at the Flutter lifecycle, it's not clear where it makes sense to track a screen view.
For a StatelessWidget
, I think build()
might make sense as I guess it's only called one time per screen view.
What about for a StatefulWidget
though? In this case build()
would not be useful as it could be called many times. Other candidates are initState()
, createState()
or the constructor which all appear to only be called once although I'm guessing they may all be called more than once per screen view as widgets up the hierarchy are re-built.
The answer is: it depends. For a StatelessWidget
, it might be suitable to have an Analytics event in build()
, but only if the parent widgets are not re-built frequently. For a StatefulWidget
the same applies but you also have to factor in re-builds due to state change (which are, more than likely often).
Really, the safest path is not to call Analytics events in any parts of the widget lifecycle, but instead on the UI event that might trigger a screen, for example, an edit button that opens up an edit screen. However, the problem with that approach is that the screen might be opened from a variety of locations within the app (meaning you have to duplicate Analytics calls across all those locations).
This means the best option is probably to tie Analytics to PageRoute
transitions so that it is called consistently whenever a page route is executed. This is demonstrated in the docs. This will miss tracking screens within a tab bar and other types of UI navigation but as the docs also say, one way to handle this is to implement RouteAware
and subscribing it to FirebaseAnalyticsObserver
(example tabs implementation).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With