Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use GetX Flutter to get app status if acive or minimized in the background

If a custom getx controller for a widget is having counter increment based on timer runs every certain seconds.

The problem is that the counter increment function keeps running even if app is in the background or screen locked.

I know how stop/cancel the timer but want to do it if the app is not active. So using GetX package how to get the app status like running, closed by user, running in background but not active on the screen, etc.

Thank you.

like image 727
Abdulrahman Alghamdi Avatar asked Mar 01 '23 14:03

Abdulrahman Alghamdi


1 Answers

You can create a GetX class that extends SuperController. This has 4 methods that you override to track the lifecycle of the app. Add your timer functions inside these methods to control it when app is in the background etc...

Check out the flutter AppLifecycleState docs for an explanation on each state.

class LifeCycleController extends SuperController {

  @override
  void onDetached() {}

  @override
  void onInactive() {}

  @override
  void onPaused() {}

  @override
  void onResumed() {}
}

Just initialize it in your main so its active from when the app starts.

void main() {
  Get.put(LifeCycleController());
  runApp(MyApp());
}
like image 61
Loren.A Avatar answered Mar 04 '23 10:03

Loren.A