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

Viewed 731

WidgetsBindingObserver is not working on my flutter web project. Is there something similar to detect when the user closes the browser like closing on the native device app with widgetbinding?

I want to rebuild the whole website after every time the browser was rebuilt regardless if the website was left open before.

1 Answers

Hook into the browser's visibility change API.

import 'dart:html';

  // inside your State class

  @override
  void initState() {
    super.initState();
    document.addEventListener("visibilitychange", onVisibilityChange);
  }

  @override
  void dispose() {
    document.removeEventListener("visibilitychange", onVisibilityChange);
    super.dispose();
  }
  
  void onVisibilityChange(Event e) {
    // do something
  }

Further reading: https://developer.mozilla.org/en-US/docs/Web/API/Document/visibilitychange_event

Related