【问题标题】:Flutter Web: How to detect AppLifeCycleState changesFlutter Web:如何检测 AppLifeCycleState 变化
【发布时间】:2021-09-22 19:48:06
【问题描述】:

我在 Flutter Web 上测试了 AppLifeCycleState,但它在移动平台上运行时无法正常工作。

这是一个正在处理的issue

我想知道是否有人知道可以做到这一点的任何解决方法或软件包?

【问题讨论】:

    标签: flutter flutter-web


    【解决方案1】:

    这是我的解决方法

    import 'dart:html';
    import 'package:flutter/foundation.dart';
    
      // inside your State class
    
      @override
      void initState() {
        super.initState();
        if (kIsWeb) {
          window.addEventListener('focus', onFocus);
          window.addEventListener('blur', onBlur);
        } else {
          WidgetsBinding.instance!.addObserver(this);
        }
      }
    
      @override
      void dispose() {
        if (kIsWeb) {
          window.removeEventListener('focus', onFocus);
          window.removeEventListener('blur', onBlur);
        } else {
          WidgetsBinding.instance!.removeObserver(this);
        }
        super.dispose();
      }
    
      void onFocus(Event e) {
        didChangeAppLifecycleState(AppLifecycleState.resumed);
      }
    
      void onBlur(Event e) {
        didChangeAppLifecycleState(AppLifecycleState.paused);
      }
    
      @override
      void didChangeAppLifecycleState(AppLifecycleState state) {
        // do your thing
      }
    

    基本上,您连接到浏览器的可见性 API 并自己调用生命周期回调。

    另见How to detect if flutter website is running in the background of browser?

    【讨论】:

    • 您好,感谢您的帮助。 onVisbilityChange 是什么?
    • 对不起,我没有用WidgetsBindingObserver 扩展类,错误消失了。我现在就测试一下。
    • 您好,如果我更改选项卡,这会起作用,有没有办法在浏览器失焦时也可以更新应用程序生命周期状态?谢谢!
    • 和上面一样,但是你连接到浏览器的focus API
    • 能否提供一个代码示例?我试过这样做,但无法弄清楚。
    猜你喜欢
    • 2023-04-04
    • 2022-01-02
    • 2019-08-24
    • 2019-06-05
    • 2018-11-21
    • 1970-01-01
    • 2022-07-20
    • 2017-06-12
    • 1970-01-01
    相关资源
    最近更新 更多