我想检测用户何时退出我的应用并在之前执行一些代码,但是我不知道该怎么做。我尝试使用此程序包:https://pub.dev/packages/flutter_lifecycle_state,但出现此错误:
flutter / .pub-cache / hosted / pub.dartlang.org / flutter_lifecycle_state-1.0.0 / lib / flutter_lifecycle_state.dart:80:30:错误:未找到Getter:“正在暂停”。案例AppLifecycleState.suspending
如果您对此问题有任何解决方案,或者知道另一种检测用户何时退出我的应用的方法,可能会很酷
无论如何,现在无法完全执行您想做的事情,现在最好的方法是使用SDK中的AppLifecycleState检查应用程序在后台/非活动状态下运行(基本上是您的库正在尝试执行的操作)
您正在使用的库已过时,因为从2019年11月起对AppLifecycleState.suspending
的拉取请求将其称为AppLifecycleState.detached
。
您可以在api.flutter.dev网站中查看AppLifecycleState枚举
这是一个如何观察包含活动的生命周期状态的示例:
import 'package:flutter/widgets.dart';
class LifecycleWatcher extends StatefulWidget {
@override
_LifecycleWatcherState createState() => _LifecycleWatcherState();
}
class _LifecycleWatcherState extends State<LifecycleWatcher> with WidgetsBindingObserver {
AppLifecycleState _lastLifecycleState;
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
super.dispose();
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
setState(() {
_lastLifecycleState = state;
});
}
@override
Widget build(BuildContext context) {
if (_lastLifecycleState == null)
return Text('This widget has not observed any lifecycle changes.', textDirection: TextDirection.ltr);
return Text('The most recent lifecycle state this widget observed was: $_lastLifecycleState.',
textDirection: TextDirection.ltr);
}
}
void main() {
runApp(Center(child: LifecycleWatcher()));
}