6

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.

1 Answers1

15

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());
}
Loren.A
  • 4,872
  • 1
  • 10
  • 17
  • Thank you so much. Was testing it I just extended the class in my controller for quick test and worked perfectly. Can't thank you enough. – Abdulrahman Alghamdi May 04 '21 at 22:28
  • No problem, happy to help. – Loren.A May 04 '21 at 22:34
  • @Loren.A Nice answer! thanks a lot but, I want to know if there is a way to detect when the app closed by user. I mean, if the user force close the app by sliding out the app from it's home screen, like what we do in iOS or android... is it detectable using GetX package and lifeCycles or not?! – Prooshani Dec 27 '21 at 22:35
  • @Prooshani that falls under the `onDetached` override. Anything you put there will happen when the user closes the app. – Loren.A Dec 28 '21 at 00:37
  • I have tried that and believe me, onDetached won't fire on force close the app. And, as everybody know, there is no good way to close the app from inside it and most of the time users force close apps by sliding them out. – Prooshani Dec 30 '21 at 00:30
  • Well not sure what you're trying to do but print statements work for me when I close the app in debug mode. – Loren.A Dec 30 '21 at 19:46
  • Will it work even app is skilled? Just like android native "service"? – Gk Mohammad Emon May 13 '22 at 11:46