Last active
April 10, 2022 13:20
-
-
Save SankethBK/1c300c565e35902cee96dc7b0b2a013f to your computer and use it in GitHub Desktop.
Passed SessionConfig as Dependency Injection and added timer for app losing focus
This file contains 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
import 'dart:async'; | |
import 'package:flutter/material.dart'; | |
import 'session_config.dart'; | |
class SessionTimeoutManager extends StatefulWidget { | |
final SessionConfig _sessionConfig; | |
final Widget child; | |
const SessionTimeoutManager( | |
{Key? key, | |
required sessionConfig, | |
required this.child, | |
}) | |
: _sessionConfig = sessionConfig, | |
super(key: key); | |
@override | |
_SessionTimeoutManagerState createState() => _SessionTimeoutManagerState(); | |
} | |
class _SessionTimeoutManagerState extends State<SessionTimeoutManager> | |
with WidgetsBindingObserver { | |
Timer? _appLostFocusTimer; | |
Timer? _userInactivityTimer; | |
bool _userTapActivityRecordEnabled = true; | |
@override | |
void initState() { | |
super.initState(); | |
WidgetsBinding.instance?.addObserver(this); | |
} | |
@override | |
void didChangeAppLifecycleState(AppLifecycleState state) { | |
super.didChangeAppLifecycleState(state); | |
if (state == AppLifecycleState.inactive || | |
state == AppLifecycleState.paused) { | |
if (widget._sessionConfig.invalidateSessionForAppLostFocus != null) { | |
_appLostFocusTimer ??= _setTimeout( | |
() => widget._sessionConfig.pushAppFocusTimeout(), | |
duration: widget._sessionConfig.invalidateSessionForAppLostFocus!, | |
); | |
} | |
} else if (state == AppLifecycleState.resumed) { | |
if (_appLostFocusTimer != null) { | |
_clearTimeout(_appLostFocusTimer!); | |
_appLostFocusTimer = null; | |
} | |
} | |
} | |
@override | |
Widget build(BuildContext context) { | |
return widget.child; | |
} | |
Timer _setTimeout(callback, {required Duration duration}) { | |
return Timer(duration, callback); | |
} | |
void _clearTimeout(Timer t) { | |
t.cancel(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment