Skip to content

Instantly share code, notes, and snippets.

@benhaxe
Last active May 20, 2020 13:05
Show Gist options
  • Save benhaxe/ad29c6a2fe5eec2f5cc13d8fc02f6dee to your computer and use it in GitHub Desktop.
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.
/// 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
*/
@benhaxe
Copy link
Author

benhaxe commented May 20, 2020

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