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

Issue

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.

Solution

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());
}

Answered By – Loren.A

Answer Checked By – Willingham (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *