O. BERHILI
Flutter · Observability7 min read

Flutter app monitoring: Crashlytics, GA4 and Remote Config

My Flutter monitoring setup: Crashlytics hooks, typed GA4 events within Firebase limits, Performance traces, Clarity replay, shake-to-report and forced updates.

On this page

Before a Flutter app's first public release, I wire in the same set of tools: Crashlytics, a typed analytics layer, Firebase Performance traces, Microsoft Clarity session replay, shake-to-report for internal builds, Remote Config for flags and forced updates, and a GA4 dashboard in Looker Studio. Most of the effort goes into the conventions around them, such as what counts as a non-fatal or what session replay must never see.

Crashlytics: catch everything, then add context

Two hooks cover the root isolate. FlutterError.onError receives errors thrown by the framework during build, layout and paint. PlatformDispatcher.instance.onError (from dart:ui) receives uncaught asynchronous errors that never reach the framework, like a Future that fails with nobody awaiting it. I report both as fatal, because an uncaught error is a bug wherever it surfaced.

dart
Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);

  final crashlytics = FirebaseCrashlytics.instance;
  // Keep debug sessions out of the dashboard.
  await crashlytics.setCrashlyticsCollectionEnabled(!kDebugMode);

  FlutterError.onError = crashlytics.recordFlutterFatalError;
  PlatformDispatcher.instance.onError = (error, stack) {
    crashlytics.recordError(error, stack, fatal: true);
    return true; // handled, do not forward to the default handler
  };

  await crashlytics.setCustomKey(
      'flavor', const String.fromEnvironment('FLAVOR', defaultValue: 'prod'));
  runApp(const ProviderScope(child: App()));
}

Isolates you spawn yourself do not reach these hooks, so catch errors inside them and send them back to the main isolate.

Then I add context. After sign-in I call setUserIdentifier with the internal user id (never an email or phone number) and clear it on sign-out. I also set a few custom keys, out of the 64 Crashlytics accepts: flavor, locale, text direction, current route and active flags. Text direction is on the list because RTL layouts have their own class of bugs. Important user actions go into crashlytics.log() as breadcrumbs.

Most of the noise in Crashlytics comes from non-fatals. I call recordError(error, stack, reason: ...) only when the code or the API contract is wrong: a payload that fails to parse, an impossible state, an unexpected 5xx. Timeouts, lost connectivity and expired sessions are expected states, and recording them buries the real issues. The decision lives in one place, the error-mapping layer between data sources and repositories, so feature code never calls Crashlytics directly.

Event naming that holds up past 300 events

I track more than 300 analytics events in production. At that size naming breaks first, and Firebase Analytics has hard limits that a growing catalog runs into:

LimitValue
Distinct event names per app500
Parameters per event25
Event and parameter name length40 characters
String parameter value length100 characters
Reserved prefixesfirebase_, google_, ga_

The convention is object_action in snake_case, with the action in the past tense: listing_viewed, photo_uploaded, contract_signed. The object comes from the domain vocabulary, and the action from a short, closed list (viewed, created, submitted, failed, shared). Variants go into parameters: filter_applied with filter_type: price rather than price_filter_applied. That rule alone keeps 300 events well under the 500-name ceiling. Where Google defines a recommended event (login, sign_up, share), I use it, because GA4 builds reports around those names.

Each event is a class, so no event name is typed as a raw string inside a widget:

dart
abstract class AnalyticsEvent {
  const AnalyticsEvent(this.name);
  final String name;
  Map<String, Object> get parameters => const {};
}

final class ListingViewed extends AnalyticsEvent {
  const ListingViewed({required this.listingId, required this.source})
      : super('listing_viewed');
  final String listingId;
  final ListingSource source; // enum: search, map, notification

  @override
  Map<String, Object> get parameters =>
      {'listing_id': listingId, 'source': source.name};
}

class Analytics {
  Analytics(this._firebase);
  final FirebaseAnalytics _firebase;
  static final _validName = RegExp(r'^[a-z][a-z0-9_]{0,39}$');

  Future<void> log(AnalyticsEvent event) {
    assert(_validName.hasMatch(event.name), 'Invalid name: ${event.name}');
    assert(event.parameters.length <= 25, 'Too many params: ${event.name}');
    final params = event.parameters.map((key, value) => MapEntry(key,
        value is String && value.length > 100 ? value.substring(0, 100) : value));
    return _firebase.logEvent(name: event.name, parameters: params);
  }
}

Parameter values must be strings or numbers, which is why enums go through .name. With typed events, autocomplete lists the whole catalog and a renamed parameter becomes a compile error instead of a silent gap in a report. A unit test can also check that names are unique. Keep values low-cardinality (enum names, buckets like 6-10): raw search text ends up in GA4's "(other)" row. Each event costs a few lines. For a prototype with a dozen events, string constants are enough.

Custom traces for the flows users wait on

Firebase Performance measures app start on its own. Its screen traces only see the single native screen hosting Flutter, though, so your routes are invisible to it, and requests made from Dart with http or Dio are not captured automatically. I add custom traces around the flows a user waits on: reaching the first useful screen, loading search results, uploading a batch of photos.

dart
Future<T> traced<T>(
  String name,
  Future<T> Function() body, {
  Map<String, String> attributes = const {},
}) async {
  final trace = FirebasePerformance.instance.newTrace(name);
  await trace.start();
  attributes.forEach(trace.putAttribute);
  try {
    final result = await body();
    trace.putAttribute('outcome', 'success');
    return result;
  } catch (_) {
    trace.putAttribute('outcome', 'error');
    rethrow;
  } finally {
    await trace.stop(); // a trace that never stops never reports
  }
}

// Usage
await traced('photos_upload', () => uploader.uploadAll(photos),
    attributes: {'count_bucket': bucketOf(photos.length)});

A trace takes at most five custom attributes. I spend them on things I will filter by, like outcome, a size bucket or connection type, and name them with the same snake_case convention as analytics events. I also don't trace everything. Data shows up in the console hours later, so traces are good for comparing releases and say little about a single session.

Session replay with Clarity, masked by default

Analytics shows where users drop off. To see why, I watch a few sessions. Microsoft publishes an official clarity_flutter package for Android and iOS: wrap the app in ClarityWidget with a ClarityConfig(projectId: ...), or call Clarity.initialize(context, config) from the first widget.

I set up masking before the first release:

  • Wrap anything sensitive in ClarityMask: identity documents, contract details, third-party contact details, free-text fields. ClarityUnmask reveals a safe child inside a masked area.
  • Recent versions capture native web views automatically. If an e-signature or payment page runs in a web view, mask it explicitly.
  • Clarity.pause() and Clarity.resume() stop capture around screens that should never be recorded, such as a camera or document scanner.
  • Wire capture into your consent flow. The SDK exposes Clarity.consent for that.

To connect the tools, Clarity.setCustomUserId gets the same opaque id as Crashlytics. Once a session has started, Clarity.getCurrentSessionUrl() goes into a Crashlytics custom key, so a crash report links straight to its replay. In a regulated product, have whoever owns privacy review the setup first.

Shake-to-report, so bug reports come with context

A chat message saying "the upload is broken" costs an hour of back-and-forth. With a shake gesture, the tester sends a report that already holds a screenshot, device and app info and the recent logs, which is something a developer can act on.

dart
class ShakeDetector {
  ShakeDetector({required this.onShake, this.threshold = 15});

  final VoidCallback onShake;
  final double threshold; // m/s^2, gravity already removed
  StreamSubscription<UserAccelerometerEvent>? _sub;
  DateTime _lastShake = DateTime(2000);

  void start() {
    _sub ??= userAccelerometerEventStream().listen((e) {
      final force = sqrt(e.x * e.x + e.y * e.y + e.z * e.z);
      final now = DateTime.now();
      if (force > threshold && now.difference(_lastShake).inSeconds >= 3) {
        _lastShake = now;
        onShake();
      }
    });
  }

  Future<void> stop() async {
    await _sub?.cancel();
    _sub = null;
  }
}

Future<Uint8List?> captureScreen(GlobalKey boundaryKey) async {
  final boundary =
      boundaryKey.currentContext?.findRenderObject() as RenderRepaintBoundary?;
  final image = await boundary?.toImage(pixelRatio: 1.5);
  final data = await image?.toByteData(format: ImageByteFormat.png);
  return data?.buffer.asUint8List();
}

What happens after the shake:

  1. The screenshot comes from a RepaintBoundary around the app. Platform views such as Google Maps or web views often come out blank, so the report form lets the user add a sentence.
  2. Device and app info come from device_info_plus and package_info_plus, plus locale, route, user id and active flags.
  3. Logs come from a bounded in-memory ring buffer (the last 200 lines or so) fed by the app logger.
  4. After the user confirms, the report goes to a backend endpoint that forwards it to the team channel. Never embed a chat webhook URL in the app, because anyone can pull it out of the binary.

The detector runs only for internal builds or staff accounts, behind a Remote Config flag, and stops when the app goes to the background.

Remote Config for flags and forced updates

For flags I stick to three rules. Defaults live in code, so the app still works if no fetch ever succeeds. Each flag is read through a typed accessor (flags.newSearchEnabled), never through a raw key in a widget. And once a rollout is done the flag gets deleted, because every flag is a branch you keep testing.

The forced-update check uses the same service. I compare integer build numbers rather than version strings, and a platform condition in the console lets min_build differ between Android and iOS under one key.

dart
enum UpdateStatus { upToDate, suggested, forced }

Future<UpdateStatus> checkForUpdate(FirebaseRemoteConfig rc) async {
  await rc.setConfigSettings(RemoteConfigSettings(
    fetchTimeout: const Duration(seconds: 5),
    minimumFetchInterval: const Duration(hours: 1),
  ));
  await rc.setDefaults(const {'min_build': 0, 'suggested_build': 0});

  try {
    await rc.fetchAndActivate();
  } catch (_) {
    // Fail open: cached or default values still apply.
  }

  final info = await PackageInfo.fromPlatform();
  final build = int.tryParse(info.buildNumber) ?? 0;

  if (build < rc.getInt('min_build')) return UpdateStatus.forced;
  if (build < rc.getInt('suggested_build')) return UpdateStatus.suggested;
  return UpdateStatus.upToDate;
}

forced shows a non-dismissible page with a store link. That page depends on nothing that could itself be broken, so no API call and no remote image. suggested shows a dismissible prompt, once per version. Failing open is deliberate: if Remote Config is down, nobody should get locked out. Before raising min_build, check the version split in GA4 to see how many people you are about to block. Kill switches also listen to onConfigUpdated. Everything else activates at startup, so the UI never changes under the user's thumb.

A Looker Studio dashboard for the product team

Firebase Analytics events land in the linked GA4 property, and Looker Studio reads GA4 natively, so product managers can answer their own questions without opening the Firebase console. I usually build four pages:

  • Overview: active users, sessions, and the split by platform and app version. The version split is also what I check before forcing an update.
  • Flows: one table per flow, with its events in order, event count and users, so the drop-off between steps is visible at a glance.
  • Feature adoption: usage of flagged features, segmented by flag value.
  • Glossary: what each event and parameter means, updated in the same pull request as the event class.

Two things catch people out. A parameter only becomes a dimension after you register it as a custom dimension in GA4. Registration is not retroactive, and a standard property allows 50 event-scoped ones. So I register what we will report on the day the event ships, and reuse generic parameter names (source, step, outcome) so one dimension covers many events. The other is latency: GA4 is not real time. When the questions outgrow the connector, the BigQuery export has the raw events.

Pre-release checklist

  • FlutterError.onError and PlatformDispatcher.instance.onError wired to Crashlytics before runApp, collection off in debug.
  • Non-fatals recorded only from the error-mapping layer, and only for bugs.
  • The same opaque user id in Crashlytics and Clarity, plus custom keys for flavor, locale, route and flags.
  • Events named object_action, variants in parameters, typed classes checked against Firebase limits.
  • Traces on the flows users wait on, with stop() in finally and five attributes at most.
  • Sensitive widgets and web views masked in Clarity.
  • Shake-to-report behind a flag, with reports sent through the backend.
  • Remote Config defaults in code, a forced update that fails open, finished flags deleted.
  • GA4 custom dimensions registered the day each event ships.
01

If you need this on your app

Open to roles & contracts

Need a senior mobile developer?

I join teams as a senior Flutter or iOS developer, or take on contract work, from architecture and CI to store releases.