flutterflutter-hooks

Using flutter HookWidget and didChangeAppLifecycleState


How can I monitor the life cycle states of the app from a particular page using HookWidget the way you can with a Stateful widget?

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

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

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    if (state == AppLifecycleState.paused) {
         ...
    }
    if (state == AppLifecycleState.resumed) {
        ...
    }
    if (state == AppLifecycleState.detached) {
       ...
    }
  }

Solution

  • First make a class:

    class MyObserver implements WidgetsBindingObserver {
    }
    

    Then create it and register it with:

    Widget build(BuildContext) {
      useEffect(() {
        final observer = MyObserver();
        WidgetsBinding.instance.addObserver(observer);
        return () => WidgetsBinding.instance.removeObserver(observer);
      }, const []);
    
      ...
    }