flutter 未调用AppLifeCycleState.detached

jk9hmnmh  于 2023-08-07  发布在  Flutter
关注(0)|答案(2)|浏览(164)
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(),
      ),
    );
  }
}

字符串
我的APP在上面。我试图检测当我的应用程序在Android上被杀死与概述按钮,并通过滑动关闭应用程序.问题是AppLifeCycleState.detached从未传递给我的回调。如果我通过按下根按钮关闭应用程序,它将被打印。如果我杀死它与滑动从概述按钮回调是不存在的。我实际上是在尝试获取原生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.

euoag5mw

euoag5mw1#

显然,这是一个正在进行的错误与Flutter。https://github.com/flutter/flutter/issues/57594

n1bvdmb6

n1bvdmb62#

不是bug,您分配的代码在'AppLifeCycleState.detached'的条件下调用永远不会保证执行。移动的操作系统旨在尽可能降低功耗,一段时间后,应用程序进入完全睡眠状态,这意味着即使是Flutter引擎也无法监听应用程序的生命周期。
查看官方文档中提到的选项,以便在后台执行dart代码:在后台执行dart代码

相关问题