对从服务器获取数据进行简单限制

不要停下来

在我的应用程序的下面部分中,我想对从服务器上获取数据进行简单的限制,当我单击按钮时,实际上,当我单击按钮时,我想检查简单变量 lastGetDataTimeStamp

我的代码和从服务器获取数据仅适用于第一个初始应用程序和方法,我该如何解决呢?

  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;
    }
  }
珍娜·雷迪

更好地利用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*/
    ...
  }


本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章