Tree
Tree

Reputation: 31361

How to detect when flutter app comes back from background?

I would like to detect when flutter app comes back from background.

In other SDKs for crossApp development, there is usually a listener when app changes this state. Is there anything similar in flutter?

Upvotes: 7

Views: 5345

Answers (1)

Tree
Tree

Reputation: 31361

class _AppState extends State<App> with WidgetsBindingObserver {
      
  @override
  void initState() {
    super.initState();
    //add an observer to monitor the widget lyfecycle changes
    WidgetsBinding.instance!.addObserver(this);
  }

  @override
  void dispose() {
    //don't forget to dispose of it when not needed anymore
    WidgetsBinding.instance!.removeObserver(this);
    super.dispose();
  }

  late AppLifecycleState _lastState;    
  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);

    if (state == AppLifecycleState.resumed && _lastState == AppLifecycleState.paused) {
      //now you know that your app went to the background and is back to the foreground
    }
    _lastState = state; //register the last state. When you get "paused" it means the app went to the background.
  }
}

Upvotes: 10

Related Questions