用户在一个时间段后自动退出登录,需要使用 Dart 计时器:
import 'dart:async'; // 以使用 Dart 内建计时器 Timer
class Auth with ChangeNotifier {
String _token;
DateTime _expiryDate;
String _userId;
Timer _authTimer; // 设置此变量,方便必要时关闭计时器,
Future<void> _authenticate(
try {
// ...
// 将自动退出功能放在 signup/sign 中,
// 如果当前时间超出认证 token 有效时间点,则自动退出登录
_autoLogout();
notifyListeners();
} catch (error) {
throw error;
}
}
void logout() {
_token = null;
_userId = null;
_expiryDate = null;
// 退出登录后,关闭 Timer
if (_authTimer != null) {
_authTimer.cancel();
_authTimer = null;
}
notifyListeners();
}
void _autoLogout() {
// 重新设置 Timer 前,关闭已存在的Timer
if (_authTimer != null) {
_authTimer.cancel();
}
final timeToExpriy = _expiryDate.difference(DateTime.now()).inSeconds;
_authTimer = Timer(Duration(seconds: timeToExpriy), logout);
}
}