【问题标题】:didChangeAppLifecycleState is not working FlutterdidChangeAppLifecycleState 不起作用 Flutter
【发布时间】:2022-01-18 10:55:41
【问题描述】:

我有超过 20 个屏幕的应用程序,如果用户在一段时间内不活动/空闲,我想执行一项任务。 我正在尝试在应用程序的根目录中获取应用程序的生命周期。但我没有在我的 logcat 上收到打印语句。我在这里做错了什么?

void main() async{
  WidgetsFlutterBinding.ensureInitialized();
 
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
 

  @override
  State<StatefulWidget> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> with WidgetsBindingObserver{


  @override
  didChangeAppLifecycleState(AppLifecycleState state) {
    switch (state) {
      case AppLifecycleState.resumed:
        print('app resumed');
        break;
      case AppLifecycleState.inactive:
        print('app inactive');
        break;
      case AppLifecycleState.paused:
        print('app paused');
        break;
      case AppLifecycleState.detached:
        print('app detached');
        break;
    }
  }
   @override
  void initState() {
    WidgetsBinding.instance.addObserver(this);
    super.initState();
    _initializeTimer();
  }
  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }
  }

【问题讨论】:

  • 您是否像这样在 main.dart 中初始化了小部件绑定观察器 WidgetsFlutterBinding.ensureInitialized(); ?
  • 是的!我也编辑了问题

标签: flutter widget application-lifecycle


【解决方案1】:

我认为这可能是因为您的应用没有更改其生命周期状态,以下是文档中对 AppLifecycleState.inactiveAppLifecycleState.paused 的说法:

inactive 应用程序处于非活动状态,未接收用户输入。

在 iOS 上,此状态对应于一个应用程序或 Flutter 主机视图 在前台非活动状态下运行。应用程序过渡到此 通话时的状态,响应 TouchID 请求,当 进入应用切换器或控制中心,或者当 托管 Flutter 应用的 UIViewController 正在转换。

在 Android 上,这对应于一个应用程序或 Flutter 主机视图 在前台非活动状态下运行。应用程序过渡到此 另一个活动被聚焦时的状态,例如分屏应用程序, 电话、画中画应用程序、系统对话框或其他 窗口。

处于此状态的应用程序应假定它们可能随时暂停。

暂停 该应用程序当前对用户不可见,不响应用户输入,并且在后台运行。当。。。的时候 应用程序处于这种状态,引擎不会调用 Window.onBeginFrame 和 Window.onDrawFrame 回调。 Android 应用程序在 这个状态应该假设他们可以在 随时。

source

因此,如果您的用户只是空闲等待,则这些状态基本上都不会变为活动状态。我想到的解决方法是使用RestartableTimer,它会在某个“非活动”时间段后触发您想要的操作,并且根据您制作屏幕的方式,您可以将其包装在GestureDetector 中捕捉用户的输入并重置计时器。

import 'package:flutter/material.dart';
import 'package:async/async.dart';

class HomePage extends StatefulWidget {
  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  late final _timer =
      RestartableTimer(const Duration(seconds: 2), _timerAction);

  void _timerAction() {
    print("User is idle");
  }

  void _resetTimer() {
    print("Caught event, reset timer");
    _timer.reset();
  }

  @override
  void initState() {
    super.initState();
    _timer.reset(); // Start the timer
  }

  @override
  void dispose() {
    _timer.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: _resetTimer,
      child: Scaffold(),
    );
  }
}

【讨论】:

    猜你喜欢
    • 2020-03-11
    • 1970-01-01
    • 2020-02-06
    • 2021-05-17
    • 2021-11-18
    • 2018-09-17
    • 2021-02-13
    • 2020-09-21
    • 2021-04-29
    相关资源
    最近更新 更多