Skip to content

Instantly share code, notes, and snippets.

@CoderNamedHendrick
Created January 9, 2024 14:03
Show Gist options
  • Save CoderNamedHendrick/29f304d52090b476ab7d00272f2da0d6 to your computer and use it in GitHub Desktop.
Save CoderNamedHendrick/29f304d52090b476ab7d00272f2da0d6 to your computer and use it in GitHub Desktop.
Interaction inactivity widget
import 'package:flutter/material.dart';
/// Widget which determines users inactivity by listening for touch actions, best used at the root(MaterialApp)
/// of your project.
/// Inactivity duration is the duration to listen for
/// onNoActiveInteraction is callback to perform action when the app hasn't been interacted with
/// for [inactivityDuration].
class InteractionInactivityWidget extends StatefulWidget {
const InteractionInactivityWidget({
super.key,
this.inactivityDuration = const Duration(minutes: 2),
this.onNoActiveInteraction,
required this.child,
});
final Duration inactivityDuration;
final VoidCallback? onNoActiveInteraction;
final Widget child;
@override
State<InteractionInactivityWidget> createState() =>
_InteractionInactivityWidgetState();
}
class _InteractionInactivityWidgetState
extends State<InteractionInactivityWidget> {
late Timer logoutTimer;
@override
void initState() {
super.initState();
WidgetsFlutterBinding.ensureInitialized().addPostFrameCallback((_) {
_initialiseTimer();
});
}
@override
void dispose() {
logoutTimer.cancel();
super.dispose();
}
void _initialiseTimer() {
logoutTimer = Timer.periodic(
widget.inactivityDuration,
(_) => widget.onNoActiveInteraction?.call(),
);
}
void _handleUserInteraction() {
if (!logoutTimer.isActive) {
_initialiseTimer();
return;
}
logoutTimer.cancel();
_initialiseTimer();
}
void _runInteractionHandler() {
_handleUserInteraction();
}
@override
Widget build(BuildContext context) {
return Listener(
onPointerDown: (_) => _runInteractionHandler(),
onPointerCancel: (_) => _runInteractionHandler(),
onPointerUp: (_) => _runInteractionHandler(),
onPointerMove: (_) => _runInteractionHandler(),
onPointerHover: (_) => _runInteractionHandler(),
onPointerSignal: (_) => _runInteractionHandler(),
behavior: HitTestBehavior.deferToChild,
child: widget.child,
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment