gpt4 book ai didi

flutter - 当 AppLifeCycleState.detached 被调用时?

转载 作者:行者123 更新时间:2023-12-04 10:00:13 33 4
gpt4 key购买 nike

我有:

class _PageState extends State<Page> 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) {
super.didChangeAppLifecycleState(state);
print('state = $state');
}

@override
Widget build(BuildContext context) => Scaffold();
}
AppLifeCycleState类有 4 个回调,其中 3 个
- active
- paused
- resumed

似乎有效,但 detached从来没有在任何情况下工作。

我读了 documentation但在实际场景中无法理解,任何人都可以分享相关代码,何时何地被调用?

最佳答案

正如医生所说

detached → const AppLifecycleState The application is still hosted on a flutter engine but is detached from any host views.

When the application is in this state, the engine is running without a view. It can either be in the progress of attaching a view when engine was first initializes, or after the view being destroyed due to a Navigator pop.



只有当您的主页小部件进入后台时,您才能在主屏幕上重现上述问题(按 Android 设备的后退按钮)
void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: HomeScreen(),
);
}
}



class HomeScreen extends StatefulWidget {
@override
_HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> with WidgetsBindingObserver {

@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
}

@override
didChangeAppLifecycleState(AppLifecycleState state) {
if (AppLifecycleState.paused == state) {}
print("Status :" + state.toString());
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Book'),
),
body: Center(
child: Text('Home Screen'),
),
);
}
}

您可以在其他屏幕上生成上述内容并在分离时调用,您可以通过在小部件的任何点击事件上以编程方式关闭应用程序来完成

安卓:
SystemChannels.platform.invokeMethod('SystemNavigator.pop');

iOS:
exit(0)

关于flutter - 当 AppLifeCycleState.detached 被调用时?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61846907/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com