如何在应用程序退出颤振之前执行代码 [英] How to execute code before app exit flutter
问题描述
我想检测用户何时退出我的应用程序并在之前执行一些代码,但我不知道如何执行此操作.我尝试使用这个包:https://pub.dev/packages/flutter_lifecycle_state 但我有这个错误:
I want to detect when a user quit my app and execute some code before but I don't know how to do this. I tried to use this package: https://pub.dev/packages/flutter_lifecycle_state but I have this error:
flutter/.pub-cache/hosted/pub.dartlang.org/flutter_lifecycle_state-1.0.0/lib/flutter_lifecycle_state.dart:80:30: 错误:找不到 Getter:'暂停'.案例 AppLifecycleState.suspending
flutter/.pub-cache/hosted/pub.dartlang.org/flutter_lifecycle_state-1.0.0/lib/flutter_lifecycle_state.dart:80:30: Error: Getter not found: 'suspending'. case AppLifecycleState.suspending
如果您对此问题有任何解决方案或知道另一种检测用户何时退出我的应用程序的方法,那就太好了
If you have any solution for this problem or know another way to detect when a user quit my app it could be cool
推荐答案
你现在不能完全做你想做的事,无论如何,现在最好的方法是检查应用程序何时在后台运行/不活动使用SDK 中的 AppLifecycleState(基本上可以完成您的库正在尝试执行的操作)
You can not do exactly what you want to do right now, anyway, the best approach right now is to check when the application it’s running in background/inactive using the AppLifecycleState from the SDK (basically does what your library is trying to do)
您使用的库已经过时,因为 2019 年 11 月的拉取请求将 AppLifecycleState.suspending
称为 AppLifecycleState.detached
.
The library that you are using it’s outdated, since a pull request from November 2019 the AppLifecycleState.suspending
it’s called AppLifecycleState.detached
.
你可以在 api.flutter 中查看 AppLifecycleState 枚举.dev 网站
以下是如何观察包含活动的生命周期状态的示例:
Here’s an example of how to observe the lifecycle status of the containing activity:
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()));
}
我认为在非活动周期删除您的数据,然后在恢复周期中重新创建它可以为您工作.
I think that deleting your data on the inactive cycle and then creating it again in the resumed one can work for you.
这篇关于如何在应用程序退出颤振之前执行代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!