gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 07:05:58 25 4
gpt4 key购买 nike

当我按下设备上的后退按钮退出应用程序时,我正在使用一个非常简单的代码来检查 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com