Last active
May 20, 2020 13:05
-
-
Save benhaxe/ad29c6a2fe5eec2f5cc13d8fc02f6dee to your computer and use it in GitHub Desktop.
Trigger an action by observing user interaction, in our case we want to auto log a user out if he stops interacting with the app within a duration using listener.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// Define top level functions at any suitable location "I did in a separate dart file" | |
Timer sessionTimer; | |
/// intialize a timer to trigger a function after a period of inactiveness | |
void initializeTimer() { | |
sessionTimer = | |
Timer.periodic(const Duration(minutes: 5), (_) => UserUtil.logOut()); | |
} | |
/// Will be called to reset the timer when some pointer events are emitted. | |
void handleUserInteraction([_]) { | |
// Check if the user is logged in and session timer is not null | |
if (CustomerState.sessionDetails.isLoggedIn && sessionTimer != null) { | |
if (!sessionTimer.isActive) { | |
return; | |
} | |
/// if timer is active cancel the previous timer | |
/// then initiale a new one | |
sessionTimer.cancel(); | |
initializeTimer(); | |
} | |
} | |
/* | |
* --- NOTE --- | |
* The session timer needs to be activated | |
* For my use case i activated it by invoking "initializeTimer()" | |
* When a user login in successfully. | |
*/ | |
class MyApp extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
/// Wrap the material app with a listener and trigger function(s) on listener's pointer events | |
return Listener( | |
/// Check the properties on the listner official documentation | |
/// to understands the pointers handled | |
/// the most imporant to me are Down & Move | |
onPointerDown: handleUserInteraction, | |
onPointerUp: handleUserInteraction, | |
onPointerMove: handleUserInteraction, | |
child: MaterialApp(...), | |
); | |
} | |
} | |
/* | |
*--- Resources --- | |
* https://flutter.dev/docs/development/ui/advanced/gestures#adding-gesture-detection-to-widgets | |
* https://api.flutter.dev/flutter/widgets/Listener-class.html | |
*/ |
Oh.
I initialize the sessionTime out when a user logs in successfully.
I will add a comment.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Wait a minute. I think the sessionTimer would never get initialized.