我可以用初始值启动 dart 秒表吗?

Sow*_*ber 2 timer stopwatch dart flutter

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

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

由于现在在后台运行 headless dart 代码有点模糊,因此我认为最好跟踪时间和时间间隙(如果在意外关闭后恢复应用程序时有任何时间间隙)。像下面这样的单独的数据对象可以跟踪时间以及秒表是否正在运行......

class StopwatchTracker{

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

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

}
Run Code Online (Sandbox Code Playgroud)

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

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

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

很想听听你们的意见!

Sow*_*ber 5

我可以!>嗯,是的,但实际上不是

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

我发现的最简单的解决方案是扩展 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;
  }

}
Run Code Online (Sandbox Code Playgroud)

目前我对这段代码不需要太多。只需在某个时刻启动秒表,然后保持运行即可。并且它可以很容易地扩展到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();
}
Run Code Online (Sandbox Code Playgroud)

想要使用代码或测试一下吗?点击这里