← Back to posts Cover image for Architecting Scalable Analytics in Flutter: Preventing the 'God Object' Anti-Pattern

Architecting Scalable Analytics in Flutter: Preventing the 'God Object' Anti-Pattern

· 4 min read
Weekly Digest

The Flutter news you actually need

No spam, ever. Unsubscribe in one click.

Chris
By Chris

Analytics usually starts as a few calls scattered through the UI: a screen view here, a checkout event there, maybe a button tap because the PM asked for it. That feels harmless until the app grows and AnalyticsService becomes a god object with vendor-specific logic, consent rules, event formatting, and half the product team’s requests baked directly into the core application.

The problem is not tracking itself. The problem is coupling features to analytics implementation details.

A better architecture treats analytics as a pipeline:

  1. Features emit neutral, typed events.
  2. A dispatcher publishes those events.
  3. Vendor adapters subscribe and translate them.
  4. Routing and consent are separate concerns.

Define a typed event catalog

Avoid free-form strings everywhere. Events should be explicit types with clear properties.

sealed class AnalyticsEvent {
  const AnalyticsEvent(this.name, this.properties);

  final String name;
  final Map<String, Object?> properties;
}

final class CheckoutCompleted extends AnalyticsEvent {
  const CheckoutCompleted({required String id, required double amount})
      : orderId = id,
        total = amount,
        super('checkout_completed', {
          'order_id': id,
          'total': amount,
        });

  final String orderId;
  final double total;
}

final class ScreenOpened extends AnalyticsEvent {
  const ScreenOpened({required String name})
      : screenName = name,
        super('screen_opened', {'screen_name': name});

  final String screenName;
}

This gives you autocomplete, refactoring safety, and a single place to understand what the app can track.

Use a dispatcher instead of calling vendors directly

Features should not know whether events go to Firebase, Segment, an internal endpoint, or a marketing tool.

class AnalyticsDispatcher {
  AnalyticsDispatcher(this._consent);

  final ConsentGate _consent;
  final _events = StreamController<AnalyticsEvent>.broadcast();

  Stream<AnalyticsEvent> get stream => _events.stream;

  void dispatch(AnalyticsEvent event) {
    if (!_consent.allows(event)) return;
    _events.add(event);
  }

  Future<void> dispose() => _events.close();
}

class ConsentGate {
  ConsentGate({Set<String> allowedEvents = const {}})
      : _allowedEvents = allowedEvents.toSet();

  final Set<String> _allowedEvents;

  bool allows(AnalyticsEvent event) =>
      _allowedEvents.contains(event.name);

  void updateAllowedEvents(Set<String> events) {
    _allowedEvents
      ..clear()
      ..addAll(events);
  }
}

Now your feature code is simple:

dispatcher.dispatch(
  CheckoutCompleted(id: order.id, amount: order.total),
);

No vendor imports. No consent checks. No formatting logic.

Let vendor adapters subscribe

Each analytics sink only knows how to send one event to one destination.

abstract class AnalyticsSink {
  Future<void> send(AnalyticsEvent event);
}

class FirebaseAnalyticsSink implements AnalyticsSink {
  @override
  Future<void> send(AnalyticsEvent event) async {
    // Convert event.properties to Firebase logEvent.
  }
}

class InternalTrackingSink implements AnalyticsSink {
  @override
  Future<void> send(AnalyticsEvent event) async {
    // POST to your own tracking endpoint.
  }
}

Routing becomes data, not a giant switch statement.

class AnalyticsRouter {
  AnalyticsRouter(this._routes);

  final Map<String, List<AnalyticsSink>> _routes;

  void attach(Stream<AnalyticsEvent> stream) {
    stream.listen((event) async {
      final sinks = _routes[event.name] ?? const <AnalyticsSink>[];

      for (final sink in sinks) {
        try {
          await sink.send(event);
        } catch (e, st) {
          // Log and continue. One vendor should not break the pipeline.
        }
      }
    });
  }
}

Wire it up once during app startup:

final consent = ConsentGate(
  allowedEvents: {'checkout_completed', 'screen_opened'},
);

final dispatcher = AnalyticsDispatcher(consent);

final router = AnalyticsRouter({
  'checkout_completed': [
    FirebaseAnalyticsSink(),
    InternalTrackingSink(),
  ],
  'screen_opened': [
    FirebaseAnalyticsSink(),
  ],
});

router.attach(dispatcher.stream);

Common mistakes to avoid

The most common failure mode is putting vendor logic inside the event producer. If your UI says analytics.trackPurchase(...), it is already too close to the implementation.

Another mistake is letting the routing layer become another god object. A switch (event.name) with inline Firebase calls, HTTP payloads, and consent rules is just moving the problem around. Keep routing declarative.

Also, do not make events vendor-specific. An event like purchase should carry neutral data. The sink decides whether to map it to purchase_completed, ecommerce_purchase, or a custom internal schema.

Finally, handle consent early. If consent is missing, the event should never reach vendors. A dispatcher-level gate is much easier to audit than consent checks sprinkled across widgets.

Why this works

This pattern keeps your app scalable because analytics becomes a side effect, not a dependency.

Adding a new vendor means writing one sink and registering it in the route map. Changing consent rules means updating the ConsentGate. Adding a new event means extending the typed catalog. Features stay clean, analytics stays testable, and the “god object” never gets a chance to form.

This blog is produced with the assistance of AI by a human editor. Learn more

Related Posts

Cover image for Choosing the Right Storage for Flutter: Beyond SharedPreferences for Persistent Data

Choosing the Right Storage for Flutter: Beyond SharedPreferences for Persistent Data

Developers frequently struggle with persistent storage in Flutter, especially when dealing with OS-level backups and app reinstalls. This post will clarify the nuances of different storage solutions like `SharedPreferences`, `path_provider`, and `flutter_secure_storage`, focusing on how to correctly manage data lifetimes (per-install vs. per-user) and avoid issues like device IDs migrating to new phones or data being unexpectedly backed up.

Cover image for Optimizing Flutter UI Performance: Solving `ImageFiltered` Lag and Smooth Blurring

Optimizing Flutter UI Performance: Solving `ImageFiltered` Lag and Smooth Blurring

Flutter's `ImageFiltered` can cause significant lag when blurring large or frequently changing content like text. This post will explain the performance bottlenecks, provide solutions like caching blurred outputs with `RepaintBoundary` or `SnapshotWidget`, and offer practical tips to ensure smooth UI effects without sacrificing frame rates.