import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() {
return _MyHomePageState();
}
}
class _MyHomePageState extends State<MyHomePage> 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) {
print(state);
}
@override
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: () async {
//do something here before pop
return true;
},
child: Scaffold(
body: Container(),
),
);
}
}
我的应用在上面。我正在尝试使用概览按钮并通过滑动关闭应用程序来检测我的应用程序何时在 Android 上被终止。问题是 AppLifeCycleState.detached 从未传递给我的回调。如果我通过按 root 上的后退按钮关闭应用程序,它会被打印出来。如果我通过从概览按钮滑动来杀死它,则回调不存在。我本质上是在尝试获取原生 android 的 onDestroy() 调用。
这是我得到的日志:
D/SurfaceView(24406): windowStopped(true) false io.flutter.embedding.android.FlutterSurfaceView{d98238 V.E...... ........ 0,0-1080,2154} of ViewRootImpl@185dd4c[MainActivity]
I/flutter (24406): AppLifecycleState.paused
Lost connection to device.
预期日志:
D/SurfaceView(25394): windowStopped(true) false io.flutter.embedding.android.FlutterSurfaceView{2d5a56d V.E...... ........ 0,0-1080,2154} of ViewRootImpl@28f4397[MainActivity]
I/flutter (25394): AppLifecycleState.paused
I/flutter (25394): AppLifecycleState.detached
Lost connection to device.
最佳答案
显然,这是一个持续存在的 flutter 错误。 https://github.com/flutter/flutter/issues/57594
关于flutter - AppLifeCycleState.detached 未被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63999854/