我正在查看秒表的文档,并且我确信它们没有方法以初始值启动秒表。
我正在开发一个应用程序,它需要测量经过的时间。因此,秒表成为这里显而易见的选择。然而,有一个用例,在清除后台应用程序时,应用程序的用户可能会意外地关闭应用程序。
因为,在后台运行无头飞镖代码现在有点模糊,我认为最好是跟踪时间和时间间隔,如果在意外关闭后恢复应用程序时也有时间间隔的话。如下所示的单独数据对象可以跟踪时间和秒表是否正在运行.
class StopwatchTracker{
final stopwatch;
final lastUpdated;
final isRunning;
final systemTime;
StopwatchTracker({this.stopwatch, this.lastUpdated, this.isRunning, this.systemTime});
}有了这个,我就有了一个对象,它有关于秒表中lastUpdated时间的数据。将其与systemTime进行比较,后者将是设备的当前系统时间。现在,我们可以看到lastUpdated时间和systemTime之间是否存在差距。如果有差距,秒表应该“跳跃”到时间,由“差距”单位。
这个StopwatchTracker对象只会在app开始/恢复时被初始化,每隔几秒钟它就会更新lastUpdated时间。我认为逻辑是存在的,但正如我所提到的,dart中的秒表类没有用起始值初始化它的方法。
我想知道我是否可以扩展秒表类来提供一种方法来完成这个任务。或者第二个选项是更新ellapsedMillis本身或将gap in mills添加到ellapsedMillis中,然后在屏幕上显示结果。
我很想听听你们的意见!
发布于 2020-06-19 15:52:45
是的,我可以!>好吧,是的,但实际上不行。
我不能将秒表的起始值设置为在特定时间开始/恢复,甚至不能重新调整当前运行时间。
我找到的最简单的解决方案是像这样扩展类秒表:
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();
}想玩这个代码,还是测试它?单击此处
https://stackoverflow.com/questions/62452593
复制相似问题