如何在Flutter应用程序中基于时间注销



如果用户在登录后5分钟以上对应用程序没有反应或处于非活动状态,我需要将用户从应用程序注销。该应用程序将转到主登录页面。

我试图在这里实现给定的解决方案,但没有成功。请帮助我如何做到这一点。

我的代码

class AppRootState extends State<AppRoot> {

Timer _rootTimer;

@override
void initState() {
// TODO: implement initState
super.initState();
initializeTimer();
}

void initializeTimer() {

const time = const Duration(minutes: 5);
_rootTimer = Timer(time, () {
logOutUser();
});
}

void logOutUser() async {

// 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

_rootTimer?.cancel();

}

// You'll probably want to wrap this function in a debounce

void _handleUserInteraction([_]) {
if (_rootTimer != null && !_rootTimer.isActive) {
// This means the user has been logged out
return;
}

_rootTimer?.cancel();
initializeTimer();
}

@override
Widget build(BuildContext context) {
return Listener(
behavior: HitTestBehavior.translucent,
onPointerDown: _handleUserInteraction,
onPointerMove: _handleUserInteraction,
onPointerUp: _handleUserInteraction,
child: MaterialApp(
)
);
}

}

我尝试了Listener和GestureDetector,但它不起作用。用户已注销,甚至正在积极使用该应用程序。

迟到了,但可能会对其他人有所帮助。上次我遇到同样的问题。当我将Timer_rootTimer声明为全局变量并且我的代码开始工作时,我感到很惊讶。

我的代码是:

Timer _rootTimer;
void main() async {
WidgetsFlutterBinding.ensureInitialized();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) => AppRoot();
}
class AppRoot extends StatefulWidget {
// This widget is the root of your application.
@override
AppRootState createState() => AppRootState();
}
class AppRootState extends State<AppRoot> {
@override
void initState() {
// TODO: implement initState
super.initState();
initializeTimer();
}
void initializeTimer() {
if (_rootTimer != null) _rootTimer.cancel();
const time = const Duration(minutes:  5 );
_rootTimer = Timer(time, () {
logOutUser();
});
}
void logOutUser() async {
// Log out the user if they're logged in, then cancel the timer.


_rootTimer?.cancel();
}
// You'll probably want to wrap this function in a debounce
void _handleUserInteraction([_]) {
if (_rootTimer != null && !_rootTimer.isActive) {
// This means the user has been logged out
return;
}
_rootTimer?.cancel();
initializeTimer();
}
@override
Widget build(BuildContext context) {
return Listener(
behavior: HitTestBehavior.translucent,
onPointerDown: _handleUserInteraction,
onPointerMove: _handleUserInteraction,
onPointerUp: _handleUserInteraction,
child:MaterialApp(
title: 'example',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: HomePage()
),
);
}
}

最新更新