I need to create an app that navigates a user to after a period of inactivity.
I tried wrapping my app in GestureDetector and run a timer after a specified period as shown below but it is not working:
class _MyAppState extends State<MyApp> {
Timer _timer;
@override
void initState() {
super.initState();
_initializeTimer();
}
void _initializeTimer() {
_timer = Timer.periodic(const Duration(seconds: 20), (_) => _logOutUser);
}
void _logOutUser() {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => WelcomePage()));
_timer.cancel();
}
void _handleUserInteraction([_]) {
if (!_timer.isActive) {
return;
}
_timer.cancel();
_initializeTimer();
}
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: _handleUserInteraction,
onPanDown: _handleUserInteraction,
child: MaterialApp(
title: 'Hello',
home: WelcomePage(),
routes: <String, WidgetBuilder>{
'/welcome': (BuildContext context) => new WelcomePage(),
'/login': (BuildContext context) => new LoginPage(),
},
debugShowCheckedModeBanner: false,
),
);
}
}
My question is how best should I implement running a function after a period of inactivity within my flutter app?
And a good way to do this is to use the mixin WidgetsBindingObserver on your LandingPage of the app. The mixin provides you with an enum AppLifecycleState which can have 4 values, detached, inactive, paused and resumed which depicts the current state of the app.
For people who want the strict answer to the question of the title ("How to execute a function after a period of inactivity in Flutter"), this is the complete solution:
@override
void initState() {
super.initState();
_initializeTimer();
}
// start/restart timer
void _initializeTimer() {
if (_timer != null) {
_timer.cancel();
}
// setup action after 5 minutes
_timer = Timer(const Duration(minutes: 5), () => _handleInactivity());
}
void _handleInactivity() {
_timer?.cancel();
_timer = null;
// TODO: type your desired code here
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With