
Flutter: How to detect user inactivity
Agustin Martin
If you are familiar with any bank or wallet app there is a good chance that it has some kind of “automatic sign out” or “temporary lock screen” as a security measure. It usually works by detecting when the app loses focus and goes to the background or by detecting the user is not interacting with the screen anymore. I’m going to follow up on that last case.
We are going to need to:
- Use a single “global” instance of a timer.
- Detect gestures.
1. Use a single “global” instance of a timer
For this example, we are going to use Provider to have a way of notifying any listener that our timer expired. Also, we need to override updateShoudlNotify because ChangeNotifier we don’t want to rebuild any dependents.
timer_service_provider.dart:

We also need a simple TimerService with methods to start, stop and reset the timer. We also need a callback method for when the timer expires.
timer_service.dart:


main.dart:

2. Detect Gestures
Our approach was to use GestureDetector to handle Tapping, Pinching, and Panning or Dragging which are the base gestures that all other detectable gestures use.
We need to get our TimerService from context and add a listener that will be called when the timer expires. Additionally, we create the callback that resets the timer, this function will be called by the Gesture detector
We packed all of this in a Helper Widget that also expects a callback, in our case the callback clears session data and navigates the user to the sign-in page.


The rest is easy, we used this widget at the start of every page (so it occupies and detects gestures of the entire screen) and we simply passed the callback for when the timer expires.
Conclusion
This is one way of doing it, I’m sure there is room for improvement and other approaches. For example, another way of doing something similar without depending on gestures would be to hook the application’s lifecycle, for more on this see this StackOverflow answer.
Ready for your next software project? Our team will turn your idea into a successful product! Contact us.