Flutter Web:如何检测 AppLifeCycleState 更改

3 flutter flutter-web

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

这是一个正在解决的问题。

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

con*_*ing 12

这是我的解决方法

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
  }
Run Code Online (Sandbox Code Playgroud)

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

另请参阅如何检测flutter网站是否在浏览器后台运行?