Flutter Web:如何检测 AppLifeCycleState 更改

2023-12-21

我测试了AppLifeCycleState在 flutter web 上,它在移动平台上工作时不起作用。

这是一issue https://github.com/flutter/flutter/issues/53107目前正在研究这个问题。

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


这是我的解决方法

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 并自行调用生命周期回调。

也可以看看如何检测flutter网站是否在浏览器后台运行? https://stackoverflow.com/questions/64550286/how-to-detect-if-flutter-website-is-running-in-the-background-of-browser/66506188#66506188

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Flutter Web:如何检测 AppLifeCycleState 更改 的相关文章

随机推荐