Want to create a time-based Flutter App? You can use the Timer class to trigger a log out function after 3 minutes of inactivity. Something you can try is to wrap your entire app in a GestureDetector that resets the timer on any event. You’d just have to make sure that any other GestureDetectors in your app use HitTestBehavior.translucent so the events are propagated to your root listener.
Here is a full example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 | import 'dart:async'; import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) => AppRoot(); } class AppRoot extends StatefulWidget { @override AppRootState createState() => AppRootState(); } class AppRootState extends State<AppRoot> { Timer _timer; @override void initState() { super.initState(); _initializeTimer(); } void _initializeTimer() { _timer = Timer.periodic(const Duration(minutes: 3), (_) => _logOutUser); } void _logOutUser() { // Log out the user if they're logged in, then cancel the timer. // You'll have to make sure to cancel the timer if the user manually logs out // and to call _initializeTimer once the user logs in _timer.cancel(); } // You'll probably want to wrap this function in a debounce void _handleUserInteraction([_]) { if (!_timer.isActive) { // This means the user has been logged out return; } _timer.cancel(); _initializeTimer(); } @override Widget build(BuildContext context) { return GestureDetector( onTap: _handleUserInteraction, onPanDown: _handleUserInteraction, onScaleStart: _handleUserInteraction, // ... repeat this for all gesture events child: MaterialApp( // ... from here it's just your normal app, // Remember that any GestureDetector within your app must have // HitTestBehavior.translucent ), ); } } |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.