Adding a Navigator Observer

Ever wanted to track page views or add navigation breadcrumbs to your error logs?

This can be done by implementing a NavigatorObserver. โœ…

Hereโ€™s some sample code showing how to implement this. ๐Ÿ‘‡

Adding a Navigator Observer
import 'package:flutter/material.dart';
import 'dart:developer';
 
class LoggerNavigatorObserver extends NavigatorObserver {
  @override
  void didPush(Route<dynamic> route, Route<dynamic>? previousRoute) {
    _logNavigation(route.settings.name, 'push');
  }
 
  @override
  void didPop(Route<dynamic> route, Route<dynamic>? previousRoute) {
    _logNavigation(route.settings.name, 'pop');
  }
 
  @override
  void didReplace({Route<dynamic>? newRoute, Route<dynamic>? oldRoute}) {
    if (newRoute != null) {
      _logNavigation(newRoute.settings.name, 'replace');
    }
  }
 
  void _logNavigation(String? routeName, String action) {
    if (routeName != null) {
      log("Screen $action: $routeName", name: 'Navigation');
    }
  }
}

To use the navigator observer, simply add it to the MaterialApp widget.

As a result, navigation logs will show in the console.

Adding a Navigator Observer

A couple of extra tips:

  • some packages already offer a navigator observer (e.g. SentryNavigatorObserver), so you may not need to implement your own
  • whatever you do, DONโ€™T track page views on the build method (this can be called many times when widgets rebuild, and is out of your control)

I will cover analytics and error monitoring in detail in my upcoming course.

If you want to ship your apps with confidence, check it out and join the waitlist. ๐Ÿ‘‡

Want More?

Invest in yourself with my high-quality Flutter courses.

Flutter Foundations Course

Flutter Foundations Course

Learn about State Management, App Architecture, Navigation, Testing, and much more by building a Flutter eCommerce app on iOS, Android, and web.

Flutter & Firebase Masterclass

Flutter & Firebase Masterclass

Learn about Firebase Auth, Cloud Firestore, Cloud Functions, Stripe payments, and much more by building a full-stack eCommerce app with Flutter & Firebase.

The Complete Dart Developer Guide

The Complete Dart Developer Guide

Learn Dart Programming in depth. Includes: basic to advanced topics, exercises, and projects. Last updated to Dart 2.15.

Flutter Animations Masterclass

Flutter Animations Masterclass

Master Flutter animations and build a completely custom habit tracking application.