我正在尝试检测我的 Flutter 应用程序何时从最近的应用程序列表中删除。我尝试将 AppLifecycleState.detached 与 WidgetsBindingObserver 结合使用,但似乎永远不会触发分离状态。以下是我使用的代码:
import 'package:flutter/material.dart';
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> with WidgetsBindingObserver {
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
super.dispose();
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
if (state == AppLifecycleState.detached) {
// App was closed from recent tabs
}
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('My App'),
),
body: Center(
child: Text('Hello, World!'),
),
),
);
}
}
但是,当我从最近的应用程序列表中删除该应用程序时,AppLifecycleState.detached 永远不会被触发。如何正确检测这种情况?有替代方法或解决方案来解决这个问题吗?
尝试使用
state == AppLifecycleState.resum
和 state == AppLifecycleState.paused
示例 -
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
if (state == state == AppLifecycleState.paused) {
// App was closed from recent tabs
} if (state == state == AppLifecycleState.resum) {
// App was closed from recent tabs
}
}