title: Flutter - run a function every time the page changes
body: <p>I want to run a function every time the page changes in my <code>Flutter application</code>.</p>
  
  <p>Ideally, I don't want to call this function in <code>initState</code> of every page, as sometimes people can forget to add the call in a new page.</p>
  
  <p>Think of it as <code>middleware</code> - be basically before the page loads etc, some code needs to run.</p>
  
  <p>Updated code for review</p>
  
  <pre><code>import 'package:flutter/material.dart';
  import 'package:flutter_secure_storage/flutter_secure_storage.dart';
  import 'package:myapp/pages/login_page.dart';
  import 'package:myapp/pages/dashboard_page.dart';
  import 'package:myapp/styles/constants.dart';
  import 'package:myapp/services/auth_service.dart';
  
  Future&lt;void&gt; main() async {
    // create a auth service instance
    AuthService authService = AuthService(secureStorage: FlutterSecureStorage());
    bool isLoggedIn = await authService.isUserLoggedIn();
  
    // run the app
    runApp(MyApp(
      isLoggedIn: isLoggedIn,
    ));
  }
  
  class MyApp extends StatefulWidget {
    final bool isLoggedIn;
  
    MyApp({this.isLoggedIn});
  
    @override
    _MyAppState createState() =&gt; _MyAppState();
  }
  
  class _MyAppState extends State&lt;MyApp&gt; with RouteAware {
    final RouteObserver&lt;PageRoute&gt; routeObserver = RouteObserver&lt;PageRoute&gt;();
  
    @override
    void didChangeDependencies() {
      super.didChangeDependencies();
      routeObserver.subscribe(this, ModalRoute.of(context));
    }
  
    @override
    void dispose() {
      routeObserver.unsubscribe(this);
      super.dispose();
    }
  
    @override
    void didPush() {
      print('didPush');
    }
  
    @override
    void didPopNext() {
      print('didPopNext');
    }
  
    @override
    Widget build(BuildContext context) {
      return MaterialApp(
        title: 'App NAME',
        theme: ThemeData(
          primarySwatch: Colors.green,
          primaryColor: kPrimeColour,
        ),
        home: widget.isLoggedIn == true ? DashboardPage() : LoginPage(),
        navigatorObservers: [routeObserver],
      );
    }
  }
  
  </code></pre>