Handling Session Timeout in App | Flutter

Anas Iqbal
2 min readMay 26, 2021

--

Hello Everyone!

What is a session timeout? well in simple words its time where user remains inactive so system ends the session of the user and he/she has to login again, most of the time session time out is handled on service side, where login token gets expired if there isn’t any api request landed on server in a particular time, but some app also have session timeout in the app, like if there isn’t any activity by detected by app then it will logout the user and throw him to the login page.

So I am gonna share you how I have handled session timeout in my Flutter app, for this example I’ll just make a simple app where user will be logout if app hasn’t detected any activity in a specified time.

First we need to come up with a way to detect user activity and simple way to do that is to use GestureDetector() and via this function it will help us to listen to user events, secondly we need to wrap up our all screens with it so we will just create a basic screen with GestureDetector() inside the stateful widget’s build() method and then we will make a rootWidget() that will be inside the build() method and every other screen will be implementing this method instead of default build method, we will achieve this by using mixings and abstract class, so lets begin with the code.

As you can see I have just write a simple session timer class consisting a timer and it will have a reset function that will reset the time every time our base GestureDetector() is triggered, if there is not gesture detected then timer will continue and once time is up it will just execute the logout function, for now I am setting up the timer time to 1 minute.

Now I’ll create an abstract base class and with a GestureDetector() widget and I’ll pass the userActivityDetected() method in its callbacks so whenever gesture is detected it runs our userActivityDetected() method and our very other screen will be implementing this class and complete the build method.

So now our work for session time out has been done, now will just make our every screens that needs to work with session timeout will be using this base class. For example below its just a sample home page thats implementing our base class.

Still there any important part left thats it to start out timer, so for now just for the basic understanding i’ll just create a login page and on its button click it will start timer and take him to the homepage.

I guess we are done here, of course you always free to modify or tweak it as per your requirement, but I hope this you help in someway when dealing with in app session time out.

Thanks :)

--

--