# Magic Analytics documentation > Magic Analytics sends GA4 from a Magic app: GTM from your own domain on web, Firebase on iOS and Android, ad signals always denied. # Installation Add `magic_analytics` to a Magic app, run the installer, set the keys and serve Google Tag Manager from your own domain on web. - [Install](#install) - [Requirements](#requirements) - [Register the Config and the Provider](#register-the-config-and-the-provider) - [Configuration](#configuration) - [Web Gateway](#web-gateway) - [iOS and Android](#ios-and-android) - [Identify the User](#identify-the-user) - [Verify](#verify) - [Related Documentation](#related-documentation) ## Install ```bash flutter pub add magic_analytics dart run magic:dowel plugin:install magic_analytics ``` The installer reads the package's `install.yaml`, publishes `lib/config/analytics.dart` (your own copy, free to edit), injects `AnalyticsServiceProvider` into the `providers` list of `lib/config/app.dart` and adds `analyticsConfig` to the config factories of `lib/main.dart`. It writes no native file and cannot set up your web server: the steps below are yours. Nothing is sent until you set the keys. Unless `ANALYTICS_ENABLED` is `true`, `1` or `yes`, the provider binds a driver that sends nothing. ## Requirements | Requirement | Value | |:------------|:------| | Dart | `>=3.13.0` | | Flutter | `>=3.47.0` | | Magic | `^1.0.0`, installed and bootstrapped (`lib/config/app.dart` exists) | | Firebase | `firebase_core` and `firebase_analytics`, pulled in by the package; used on iOS and Android only | | Web | A web server that can proxy one path to `GTM-XXXXXXX.fps.goog` | ## Register the Config and the Provider Add the config factory to the list `Magic.init` receives, and keep every factory your `main()` already passes: ```dart import 'package:magic/magic.dart'; import 'package:material_ui/material_ui.dart'; import 'config/analytics.dart'; // published by plugin:install Future main() async { await Magic.init( configFactories: [ () => analyticsConfig, // Keep every other config factory your main() already passes. ], ); runApp(MagicApplication(title: 'My App')); } ``` The provider entry goes in the `providers` list of `lib/config/app.dart`, after the providers that report errors, so a failure while analytics boots is still reported: ```dart import 'package:magic_analytics/magic_analytics.dart'; final List providers = [ // ...your other providers, error reporting first (app) => AnalyticsServiceProvider(app), ]; ``` `boot()` adds a page view observer to `MagicRouter`, which refuses one after it has built its `routerConfig`: keep the provider in the list instead of adding the observer yourself. ## Configuration `lib/config/analytics.dart` reads these `.env` keys: | Key | Default | Purpose | |:----|:--------|:--------| | `ANALYTICS_ENABLED` | `false` | The master switch. Only `true`, `1` or `yes` enable a real driver; any other value keeps the one that sends nothing. | | `GTM_CONTAINER_ID` | `''` | The container, `GTM-XXXXXXX`. Web only. | | `GTM_GATEWAY_PATH` | `''` | The first-party path that serves the container, such as `/metrics`. Web only. | The container loads only when both GTM keys are filled, so it is never requested from Google's own host. The keys go through `Env.filled`, which reads a blank value (`KEY=""`) as nothing. The map also holds `firebase_options`, `null` by default, which turns the mobile driver on once it is set; see [iOS and Android](#ios-and-android). `Env` reads the `.env` you bundle, not `--dart-define`, so write the keys into the file the build ships. ## Web Gateway On web the container is served from a path on your own origin and never from `googletagmanager.com`. Proxy that path to your container's Google tag gateway host, `GTM-XXXXXXX.fps.goog`, in the web server in front of the app, then point the config at it: ```bash ANALYTICS_ENABLED=true GTM_CONTAINER_ID=GTM-XXXXXXX GTM_GATEWAY_PATH=/metrics ``` The driver requests `/metrics/?id=GTM-XXXXXXX` on the page's origin. The path may be written `metrics`, `/metrics` or `/metrics/`. The container must send no page view of its own: its GA4 configuration sets `send_page_view` to `false`, because the driver pushes each page view with a pattern location instead. ## iOS and Android Run FlutterFire once, then hand the generated options to the config: ```bash flutterfire configure --platforms=ios,android ``` In `lib/config/analytics.dart` set `'firebase_options': () => DefaultFirebaseOptions.currentPlatform`, with `DefaultFirebaseOptions` imported from the `firebase_options.dart` FlutterFire wrote. Leave it `null` on web: Firebase is never initialised there. The driver initialises Firebase on first use when your app has not done it. Keep collection off until the driver switches it on, and keep ads denied, with these native keys. iOS, in `Info.plist`: | Key | Value | |:----|:------| | `FIREBASE_ANALYTICS_COLLECTION_ENABLED` | `false` | | `FirebaseAutomaticScreenReportingEnabled` | `false` | | `GOOGLE_ANALYTICS_DEFAULT_ALLOW_ANALYTICS_STORAGE` | `true` | | `GOOGLE_ANALYTICS_DEFAULT_ALLOW_AD_STORAGE` | `false` | | `GOOGLE_ANALYTICS_DEFAULT_ALLOW_AD_USER_DATA` | `false` | | `GOOGLE_ANALYTICS_DEFAULT_ALLOW_AD_PERSONALIZATION_SIGNALS` | `false` | Android, as `` inside `` in `AndroidManifest.xml`: | Name | Value | |:-----|:------| | `firebase_analytics_collection_enabled` | `false` | | `google_analytics_automatic_screen_reporting_enabled` | `false` | | `google_analytics_default_allow_analytics_storage` | `true` | | `google_analytics_default_allow_ad_storage` | `false` | | `google_analytics_default_allow_ad_user_data` | `false` | | `google_analytics_default_allow_ad_personalization_signals` | `false` | Automatic screen reporting is off because the observer sends the page views, and two sources would count each one twice. ## Identify the User The package never decides who the user is. After sign-in, call `Analytics.identify` with an opaque id (a UUID), and set the user's opt-out before the first page view; see [Consent and Opt-Out](https://anilcancakir.com/magic/docs/analytics/basics/consent-and-opt-out.md). ```dart import 'package:magic_analytics/magic_analytics.dart'; Future onSignedIn(String userUuid) async { await Analytics.identify(userUuid); } ``` ## Verify Set the keys, run the app and open GA4 Realtime or the GTM preview. The Firebase driver sends once the options are set and the platform is iOS or Android; the web driver injects its script on the first event, so nothing appears in the network tab before then. ```dart import 'package:magic_analytics/magic_analytics.dart'; Future verify() async { await Analytics.track('analytics_installed'); } ``` With the keys empty `Analytics.track` completes and sends nothing. ## Related Documentation - [Facade and Provider](https://anilcancakir.com/magic/docs/analytics/basics/facade-and-provider.md): the calls, the limits and what the provider wires. - [Drivers](https://anilcancakir.com/magic/docs/analytics/basics/drivers.md): which driver runs where and what each pushes. - [Consent and Opt-Out](https://anilcancakir.com/magic/docs/analytics/basics/consent-and-opt-out.md): ads denied, the device opt-out. --- # Facade and Provider `Analytics` is the one static entry point for events, page views, identity and defaults, and `AnalyticsServiceProvider` binds it and wires the router and the auth state. - [Quick Reference](#quick-reference) - [Events and Parameters](#events-and-parameters) - [Identity](#identity) - [GA4 Limits](#ga4-limits) - [Order and Failure](#order-and-failure) - [What the Provider Wires](#what-the-provider-wires) - [Page Views](#page-views) - [Gotchas](#gotchas) - [Related Documentation](#related-documentation) ## Quick Reference ```dart import 'package:magic_analytics/magic_analytics.dart'; Future afterSignIn(String userUuid, String teamPlan) async { await Analytics.identify(userUuid); await Analytics.setUserProperties({'locale': 'en'}); await Analytics.setDefaultParams({'team_plan': teamPlan}); await Analytics.track('monitor_created', {'monitor_type': 'http'}); } ``` | Call | Does | |:-----|:-----| | `Analytics.track(name, [parameters])` | Sends the event `name` with string or number parameters | | `Analytics.screen(name, {location, referrer})` | Sends a page view; the observer calls it for you | | `Analytics.identify(userId)` | Sets the GA4 user id | | `Analytics.setUserProperties(properties)` | Sets user-level properties; a `null` value clears one | | `Analytics.setDefaultParams(parameters)` | Replaces the parameters sent with every event; `null` clears them | | `Analytics.setOptOut(optedOut)` | Stops or resumes collection on this device | | `Analytics.isOptedOut` | Whether this device has opted out | | `Analytics.reset()` | Forgets the signed-in user | | `Analytics.clientId()` | The GA4 client id, or `null` | Every call returns a future that never fails: await it in a test, ignore it in app code. A GA4 limit violation is the one exception, in debug only (see [Order and Failure](#order-and-failure)). ## Events and Parameters A parameter value is a string or a number. A string passes through the [URL scrubber](https://anilcancakir.com/magic/docs/analytics/guides/url-scrubbing.md) first, so an email address or a token inside it leaves the device masked. The limits below apply to what is actually sent. `setDefaultParams` replaces the whole set: a key left out of the new map is removed. This is where team facts go (a plan, a team size). Each event carries the defaults, and they count toward the 25 parameters an event may carry. ## Identity `identify` takes the user's opaque id, a UUID. It refuses an empty id, one longer than 256 characters and anything the scrubber would mask, so an email address is never an id. `setUserProperties` is for facts about the USER, not the team: a name is at most 24 characters and a value at most 36. Team facts belong in `setDefaultParams`, so a team switch replaces them instead of leaving the old team on the user. `reset()` nulls the user id, every user property set since the last reset and every default parameter, then lets the driver clear what is left. It never rotates the client id: the device stays the same across a sign-out. It runs on an opted-out device too. ## GA4 Limits | Limit | Value | |:------|:------| | Event name, parameter name, default parameter name | 40 characters, letters, digits and underscores, starting with a letter | | Reserved prefixes | `ga_`, `google_`, `firebase_` | | Parameters per event, defaults included | 25 | | String parameter value | 100 characters, measured after scrubbing | | User property name | 24 characters | | User property value | 36 characters | | User id | 256 characters | A call that breaks a limit fails an `assert` in debug, so a test or a debug run stops at the call site. In release the call is dropped and the reason is logged through Magic's `Log` (or `debugPrint` when none is bound). Nothing invalid reaches a driver. ## Order and Failure Driver calls run one at a time, in call order, on a queue inside `AnalyticsManager`. An auth listener cannot await `reset()`, and without the queue the next user's `setDefaultParams` could reach the driver before the previous user's were cleared. A driver error is caught at the manager, logged and never rethrown, so an analytics call never throws into UI flow. A limit violation is the one deliberate exception, in debug only. ## What the Provider Wires | Step | Does | |:-----|:-----| | `register()` | Binds the `analytics` singleton, an `AnalyticsManager` over the driver `createAnalyticsDriver` picks for the platform, or `NullDriver` unless `analytics.enabled` is `true` | | `boot()` | Adds `AnalyticsNavigatorObserver` to `MagicRouter`, once | | `boot()`, with `auth` bound | Calls `Analytics.reset()` when the signed-in user signs out or changes | The reset follows `Auth.stateNotifier` and compares the user id, so a team switch (same user) keeps the identity: the app sets the new team's default parameters itself. The provider never calls `identify`. ## Page Views `AnalyticsNavigatorObserver` reports a page view each time a named page comes to the top. Magic names a page by its route name, or by its path pattern when the route has no name, and that name is the title; the location is always the pattern (`/monitors/:id`, never `/monitors/42`): no id, token or email in either, and every monitor's page counts as one page. A page without a name (a dialog, a bottom sheet) is not a page view, and closing one does not report the page beneath again. The previous page's pattern is the next page's referrer. ## Gotchas | Mistake | Fix | |:--------|:----| | Putting a team plan in `setUserProperties` | Use `setDefaultParams`; user properties are user-level | | Calling `setDefaultParams` with only the new key | It replaces the set; pass every default you want kept | | Passing an email to `identify` | Pass the user's UUID; the call is refused otherwise | | A parameter that is a `bool` or a list | Send a string or a number; anything else breaks the limit | | Adding the observer in `main()` | Register the provider; `MagicRouter` refuses an observer after its config is built | | Expecting `reset()` to change the client id | It does not; the device is the same | ## Related Documentation - [Drivers](https://anilcancakir.com/magic/docs/analytics/basics/drivers.md): what each driver does with these calls. - [Consent and Opt-Out](https://anilcancakir.com/magic/docs/analytics/basics/consent-and-opt-out.md): what `setOptOut` stops. - [URL Scrubbing](https://anilcancakir.com/magic/docs/analytics/guides/url-scrubbing.md): what is masked before anything is sent. - [Testing](https://anilcancakir.com/magic/docs/analytics/guides/testing.md): asserting events without a live property. --- # Drivers Three drivers sit behind the facade: Google Tag Manager on web, Firebase on iOS and Android, and a null driver when nothing is configured. - [Quick Reference](#quick-reference) - [Picking the Driver](#picking-the-driver) - [Web Driver](#web-driver) - [Container Setup](#container-setup) - [Firebase Driver](#firebase-driver) - [Null Driver](#null-driver) - [Writing a Driver](#writing-a-driver) - [Gotchas](#gotchas) - [Related Documentation](#related-documentation) ## Quick Reference | Platform | Driver | Runs when | |:---------|:-------|:----------| | Web | `GtmWebDriver` | `analytics.enabled` is `true` and `gtm.container_id` and `gtm.gateway_path` are both set | | iOS, Android | `FirebaseDriver` | `analytics.enabled` is `true` and `firebase_options` is a `FirebaseOptions Function()` | | Anything else, or not configured | `NullDriver` | Always | A driver only transports. The facade has already validated, scrubbed and gated each call, so a driver re-checks none of it. ## Picking the Driver `AnalyticsServiceProvider` reads the `analytics` config map and calls `createAnalyticsDriver`, which is a conditional export: the `dart.library.js_interop` arm is the web build, `dart.library.io` is iOS and Android, and a stub that answers `NullDriver` is the default. The web arm keys on `js_interop` and not on the legacy `dart:html`, which a WebAssembly build lacks. The result is that the Firebase code is never reachable from a web build, so Firebase is never initialised there. Without `analytics.enabled: true` the provider skips all of this and binds `NullDriver`. ## Web Driver `GtmWebDriver` loads a Google Tag Manager container from your first-party gateway path and feeds GA4 through it. **Lazy load.** Nothing touches the page until the first call that sends something, so a device that opted out never loads the container and never gets a `dataLayer`. Then, in order: an inline script defines `window.dataLayer` and the `gtag` shim, defaults consent (analytics granted, every ad signal denied), pre-seeds the page fields (below) and pushes `gtm.start`; only after that is the loader `