DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 968,547 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Cover image for How to implement Auto Logout in Flutter
Eshank Vaish
Eshank Vaish

Posted on • Originally published at Medium

How to implement Auto Logout in Flutter

Auto logout is a functionality implemented on various apps and websites to log out the user automatically when there is no activity from the user’s end for a specified period. The activity can be mouse movement, touch, click, API call, etc and auto-logout is implemented on the backend and frontend. For the course of this article, we will be talking about implementing it on the front end.

Implementing Auto Logout

Auto logout works by using a timer for the specified period that resets each time a user activity is detected and a new timer is initiated. In case there is no user activity, the user is logged out and an appropriate message is displayed to the user. So adding two functionalities (User Activity Detection and Timer Manager Service) to a flutter app would add the auto-logout support to any flutter app assuming the authentication part is already set up.

Let’s start with adding the timer manager service, let’s call it AutoLogoutService. This service would be responsible for providing the utilities for setting/resetting the logout timer based on user activity. Here is the code snippet for the same:

We are now going to add the user activity detector wrapper widget. The widget would basically act as a wrapper to the whole app, detect the click/tap events in the app, and call AutoLogoutService when activity is detected. Here is the code snippet for the same:

Once all of this is done, we just need to wrap the MaterialApp with the UserActivityDetector and the auto-logout feature would be up and running.

@override
Widget build(BuildContext context) {
  return **UserActivityDetector(**
    **child: **MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    ),
  **)**;
}
Enter fullscreen mode Exit fullscreen mode

Now whenever a tap/click event is detected in the app, the user activity detector is called. Here is the link to complete implementation on Github.

Thanks for reading. Want to connect? React out on Twitter, LinkedIn or in the comments below!

Top comments (2)

Collapse
 
kenng1 profile image
Ken

Why is FocusScope.of(context).requestFocus(focusNode); needed?

It seems to break TextFormFields keyboard showing up on mobile.

Collapse
 
eshankvaish profile image
Eshank Vaish Author

Thanks for pointing it out @kenng1. I'll review it up and update.

Update Your DEV Experience Level:

Settings

Go to your customization settings to nudge your home feed to show content more relevant to your developer experience level. πŸ›