使用 flutter HookWidget 和 didChangeAppLifecycleState

gg1*_*g11 7 flutter flutter-hooks

如何使用HookWidget从特定页面监控应用程序的生命周期状态,就像使用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) {
       ...
    }
  }
Run Code Online (Sandbox Code Playgroud)

Rém*_*let 7

首先做一个类:

class MyObserver implements WidgetsBindingObserver {
}
Run Code Online (Sandbox Code Playgroud)

然后创建它并注册它:

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

  ...
}
Run Code Online (Sandbox Code Playgroud)


joh*_*ohn 6

Flutter hooks 附带一个内置didchangeapplifecycle 访问权限,如下所示

    final appLifecycleState = useAppLifecycleState();

    useEffect(() {
      print("current app state");
      print(appLifecycleState);
      if (appLifecycleState == AppLifecycleState.paused || appLifecycleState == AppLifecycleState.inactive) {
        //...
      } else if (appLifecycleState == AppLifecycleState.resumed) {
        //...
      }
      return null;
    }, [appLifecycleState]);
Run Code Online (Sandbox Code Playgroud)