dart - Flutter 生命周期暂停方法未被调用

标签 dart flutter

当我按下设备上的后退按钮退出应用程序时,我正在使用一个非常简单的代码来检查 Flutter 生命周期回调中 suspending 方法的工作情况。但它没有被调用。

class _HomePageState extends State<HomePage> with WidgetsBindingObserver {
  WidgetsBinding binding = WidgetsBinding.instance;

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    print("state: $state");
  }

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

  @override
  Widget build(BuildContext context) {
    return Center(child: Text("Center"));
  }

  @override
  void dispose() {
    binding.removeObserver(this);
    super.dispose();
  }
}

最佳答案

你应该试试 didPopRoute() Android 上后退按钮的生命周期钩子(Hook)。来自文档:

Called when the system tells the app to pop the current route. For example, on Android, this is called when the user presses the back button.

class _HomePageState extends State<HomePage> with WidgetsBindingObserver {
  WidgetsBinding binding = WidgetsBinding.instance;

  @override
  Future<bool> didPopRoute() {
    // Android user pressed back button
    final bool preventAppFromClosing = true;
    return preventAppFromClosing;
  }

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

  @override
  void dispose() {
    binding.removeObserver(this);
    super.dispose();
  }
}

关于dart - Flutter 生命周期暂停方法未被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52765503/

相关文章:

image - flutter : Display Local Image when Network Image not found or error fetching it?

flutter - 错误 : The operator '[]' isn't defined for the class 'Future<dynamic>'

dart - 你如何在 dart 中加载图像服务器端?

firebase - 从 firebase 检索时,字符串在离开 child 后返回 null

flutter - FFmpeg 命令从 Android 手机捕获音频

flutter - VideoPlayerController.network()遇到源错误

dart - 将参数/输入数据传递到DART中的自定义元素

user-interface - 如何在 flutter 中去除卡片的内部填充?

flutter - 如何使用 Flutter 检查 iOS/Android 上是否启用了暗模式?

error-handling - Flutter:关闭互联网连接后出错 - "Error while applying io.flutter.console.FlutterConsoleFilter@70f92821 to ' W/zzajf (5265)”