在我的应用程序的以下部分中,我想对从服务器上获取数据进行简单的限制,当我单击按钮时,实际上,当我单击按钮时,我想将简单变量检查为lastGetDataTimeStamp
< / p>
我的代码和从服务器获取数据仅适用于第一个初始应用程序和方法,我该如何解决呢?
final MyApi _api;
int lastGetDataTimeStamp = 0;
bool _isExpanded = false;
bool get isExpanded => _isExpanded;
Future<Response<BuiltAccountData>> getLatestStories(bool canGet) {
if(canGet){
DateTime currentTime = DateTime.now();
var date = new DateTime.fromMillisecondsSinceEpoch(lastGetDataTimeStamp * 1000);
var diff = currentTime.difference(date);
if (diff.inMinutes >= 3) {
lastGetDataTimeStamp = DateTime.now().toUtc().millisecondsSinceEpoch;
BuiltLogin login = BuiltLogin((b) => b
..page_name = ''
..page_password = '');
return _api.getLatestStoriesList(login);
} else {
return null;
}
}else{
return null;
}
}
答案 0 :(得分:1)
更好地利用DateTime
方法,而不是转换为小数并使逻辑变得复杂。对我来说,以下代码正在工作。
注意:您可能希望将_lastAccessedAt
设置为全局变量,因为调用此代码的对象可能会被重建。如果它一直存在,那么就不必将其设置为全局。
// Note: You might want to make this a global variable depending on this class lifetime.
DateTime _lastAccessedAt;
Future<Response<BuiltAccountData>> getLatestStories(bool canGet) {
if (!canGet) {
print("Can't get");
return Future.value(null);
}
// Remove below block. Only for debugging.
if (_lastAccessedAt != null) {
print("Diff: ${DateTime.now().difference(_lastAccessedAt).inSeconds} secs");
}
if (_lastAccessedAt != null && DateTime.now().difference(_lastAccessedAt).inMinutes < 3) {
print("Ignoring request as last access time is less than 3mins");
return Future.value(null);
}
_lastAccessedAt = DateTime.now();
print("Sending to server");
/* Your logic goes here*/
...
}