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