anonymous-dev
anonymous-dev

Reputation: 3529

Does the WidgetsBindingObserver work on a stateless widget?

I am trying to use the WidgetsBindingObserver to see if my app is brought to the foreground. But it doesn't seem do anything. Does it only work on a statefull widget?

class TheHomeView extends StatelessWidget with WidgetsBindingObserver {

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    print('lifecycle changed');
    if (state == AppLifecycleState.resumed) {
      print('resumed');
      showLatestGroupNotification();
    }
  }

Upvotes: 7

Views: 4886

Answers (1)

anonymous-dev
anonymous-dev

Reputation: 3529

Well it turns out, you can use it in a stateless widget. But you need to use

WidgetsBinding.instance.addObserver(this);

which you can do in the constructor of the widget. But if you want to remove the binding on dispose

WidgetsBinding.instance.removeObserver(this);

You would need a dispose which is only available in a statefull widget. Or you would have to do it manually.

https://dev.to/pedromassango/onresume-and-onpause-for-widgets-on-flutter-27k2

Upvotes: 4

Related Questions