Flutter Web:如何检测 AppLifeCycleState 变化

Flutter Web: How to detect AppLifeCycleState changes

我在 flutter web 上测试了 AppLifeCycleState,它在移动平台上运行时无法运行。

这是一个正在处理的issue

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

这是我的解决方法

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?