【问题标题】:Can I start the dart Stopwatch with an initial value?我可以用初始值启动飞镖秒表吗?
【发布时间】:2020-10-08 15:57:12
【问题描述】:

我正在查看Stopwatch 的文档,我确信他们没有使用初始值启动秒表的方法。

我正在开发一个需要测量经过时间的应用。因此,秒表成为这里显而易见的选择。但是,有一个用例,应用程序的用户在清除后台应用程序时可能会意外关闭应用程序。

由于现在在后台运行无头飞镖代码有点模糊,我认为跟踪时间和时间间隔是最有利的,如果在意外关闭后恢复应用程序时有任何情况。像下面这样一个单独的数据对象可以跟踪时间以及秒表是否正在运行......

class StopwatchTracker{

  final stopwatch;
  final lastUpdated;
  final isRunning;
  final systemTime;

  StopwatchTracker({this.stopwatch, this.lastUpdated, this.isRunning, this.systemTime});

}

有了这个我有一个对象,其中包含来自秒表的lastUpdated 时间的数据。 将此与systemTime 进行比较,后者将是设备的当前系统时间。 现在,我们可以查看lastUpdated 时间和systemTime 之间是否存在差距。如果有间隙,秒表应该以“间隙”单位“跳跃”到时间。

这个StopwatchTracker 对象只会在应用启动/恢复时初始化,每隔几秒,它会更新lastUpdated 时间。我认为逻辑是存在的,但是,正如我所提到的,dart 中的 Stopwatch 类没有使用起始值对其进行初始化的方法。

我想知道是否可以扩展 Stopwatch 类来容纳一个方法来做到这一点。或者第二种选择是更新ellapsedMillis 本身或将gap in mills 添加到ellapsedMillis,然后在屏幕上显示结果。

很想听听你们的意见!

【问题讨论】:

    标签: flutter dart timer stopwatch


    【解决方案1】:

    是的,我可以! > 是的,但实际上没有

    我无法将秒表的起始值设置为在某个时间开始/恢复,甚至无法重新调整当前运行时间。

    我发现的最简单的解决方案是像这样扩展 Stopwatch 类:

    class StopWatch extends Stopwatch{
      int _starterMilliseconds = 0;
    
      StopWatch();
    
      get elapsedDuration{
        return Duration(
          microseconds: 
          this.elapsedMicroseconds + (this._starterMilliseconds * 1000)
        );
      }
    
      get elapsedMillis{
        return this.elapsedMilliseconds + this._starterMilliseconds;
      }
    
      set milliseconds(int timeInMilliseconds){
        this._starterMilliseconds = timeInMilliseconds;
      }
    
    }
    

    目前我对这段代码的要求不多。只需在某个时间点启动秒表,然后继续运行。并且它可以很容易地扩展到秒表类的其他get 类型。

    这就是我计划使用课程的方式

    void main() {
      var stopwatch = new StopWatch(); //Creates a new StopWatch, not Stopwatch
      stopwatch.start();               //start method, not overridden
      stopwatch.milliseconds = 10000;  //10 seconds have passed
      print(stopwatch.elapsedDuration);//returns the recalculated duration
      stopwatch.stop();
    }
    

    想玩代码还是测试一下? Click here

    【讨论】:

    • 这是一个非常简单的解决方案:]。我只会将这个类命名为不同的名称,因为它的名称与默认名称几乎相似。您也可以将其更改为在构造函数中传递值。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-07
    相关资源
    最近更新 更多