Hey I have this simple code for didChangeAppLifecycleState that triggers a function that updates a Firestore record of when user was online last time

  @override

  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    final authServiceProvider =
        Provider.of<AuthServiceProvider>(context, listen: false);

    if (state == AppLifecycleState.resumed) {
    } else {
      authServiceProvider.updateUserLastOnline();
    }
  }

It works fine in a separate page but how I make it work for the whole app not copying this code to every single page?


Solution 1: TonyWyomy

I just converted my main widget in main.dart into Stateful widget with WidgetsBindingObserver and added the same code

 @override

  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    final authServiceProvider =
        Provider.of<AuthServiceProvider>(context, listen: false);

    if (state == AppLifecycleState.resumed) {
    } else {
      authServiceProvider.updateUserLastOnline();
    }
  }

Now it works for the whole app.