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

Flutter 对从服务器获取数据进行简单限制,flutter,dart,Flutter,Dart,在我的应用程序下面的这一部分中,我想对单击按钮时从服务器获取数据做一个简单的限制,事实上,当我单击按钮时,我想将简单变量检查为lastGetDataTimeStamp 我的代码和从服务器获取数据只对第一个初始应用程序和方法有效,我如何解决这个问题 final MyApi _api; int lastGetDataTimeStamp = 0; bool _isExpanded = false; bool get isExpanded => _isExpanded;

在我的应用程序下面的这一部分中,我想对单击按钮时从服务器获取数据做一个简单的限制,事实上,当我单击按钮时,我想将简单变量检查为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*/
    ...
  }