应用程序退出前如何执行代码

应用程序退出前如何执行代码

本文介绍了应用程序退出前如何执行代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想检测用户何时退出我的应用并执行一些代码,但是我不知道该怎么做.我尝试使用此软件包: 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:

如果您有解决此问题的任何方法,或者知道另一种检测用户何时退出我的应用的方法,那可能很酷

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)

您正在使用的库已过时,因为从AppLifecycleState.suspending到2019年11月的拉取请求称为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中查看AppLifecycleState枚举. flutter.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.

这篇关于应用程序退出前如何执行代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 05:22