Tying into native lifecycle events in Flutter

When embedding a Flutter engine in native, we sometimes need to tie into lifecycle events such as viewDidAppear or onResume. To do so, we can do the following in Flutter.

1.) Extend WidgetsBindingObserver

class _MyState extends State<Something> with WidgetsBindingObserver 

2.) Add an observer to get notifications for state changes

 @override
 void initState() {
   super.initState();
   WidgetsBinding.instance.addObserver(this);
 }

3.) Override didChangeAppLifecycleState

@override
void didChangeAppLifecycleState(AppLifecycleState state) {
    switch (state) {
    case AppLifecycleState.inactive:
      print("inactive");
      break;
    case AppLifecycleState.paused:
      print("paused");
      break;
    case AppLifecycleState.resumed:
      print("resumed");
      break;
    case AppLifecycleState.detached:
      print("detached");
      break;
  }
}

Photo by drmakete lab from Pexels