Flutter 中应用程序终止时执行异步方法

问题描述 投票:0回答:1

应用程序终止时是否可以运行异步方法?

我尝试使用 AppLifecycle 并在处于

AppLifecycleState.detached
状态时运行我的方法,但应用程序似乎在成功执行我的异步方法之前就终止了。它能够完全执行我的异步方法的唯一状态是当状态处于
AppLifecycleState.inactive
时。当
AppLifecycleState.inactive
对我来说还不够时执行异步方法,因为应用程序很容易进入非活动状态(例如,当我拉下通知栏时)。

我有办法实现这一目标吗?检测用户是否正在关闭/杀死应用程序,如果是,则在关闭之前执行异步方法。

flutter dart async-await
1个回答
0
投票
1. WidgetsBindingObserver with didChangeAppLifecycleState: You mentioned trying the AppLifecycleState.detached, but it seems that it's not reliably called before the app is terminated. Instead, you might want to try using WidgetsBindingObserver and listen for the didChangeAppLifecycleState callback. When the state changes to AppLifecycleState.paused, you could try executing your asynchronous method. Keep in mind that this might not be called reliably before termination.

 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.paused) {
  // Execute your async method here
  executeAsyncMethod();
   }
 }

 Future<void> executeAsyncMethod() async {
 // Your async method implementation here
 }

 @override
Widget build(BuildContext context) {
return MaterialApp(
  // Your app code here
   );
 }
}
© www.soinside.com 2019 - 2024. All rights reserved.