[英]Can I start the dart Stopwatch with an initial value?
我正在查看Stopwatch的文檔,我確信他們沒有使用初始值啟動秒表的方法。
我正在開發一個需要測量經過時間的應用程序。 因此,秒表成為這里顯而易見的選擇。 但是,有一個用例,應用程序的用戶在清除后台應用程序時可能會意外關閉應用程序。
因為,在后台運行無頭 dart 代碼現在有點模糊,我相信跟蹤時間和時間間隔是最有利的,如果在意外關閉后恢復應用程序時有的話。 像下面這樣的單獨數據 object 可以跟蹤時間以及秒表是否正在運行......
class StopwatchTracker{
final stopwatch;
final lastUpdated;
final isRunning;
final systemTime;
StopwatchTracker({this.stopwatch, this.lastUpdated, this.isRunning, this.systemTime});
}
有了這個,我有一個 object ,其中包含有關秒表的lastUpdated
時間的數據。 將此與systemTime
進行比較,后者將是設備的當前系統時間。 現在,我們可以查看lastUpdated
時間和systemTime
之間是否存在差距。 如果有間隙,秒表應該以“間隙”單位“跳躍”到時間。
此StopwatchTracker
object 只會在應用程序啟動/恢復時初始化,並且每隔幾秒,它將更新lastUpdated
時間。 我認為邏輯是存在的,但是,正如我所提到的,dart 中的秒表 class 沒有使用起始值對其進行初始化的方法。
我想知道我是否可以擴展秒表 class 以容納一種方法來做到這一點。 或者,第二個選項是更新ellapsedMillis
本身,或者將gap in mills
添加到ellapsedMillis
,然后在屏幕上顯示結果。
很想聽聽你們的意見!
我可以! >是的,但實際上沒有
我無法將秒表的起始值設置為在某個時間開始/恢復,甚至無法重新調整當前運行時間。
我發現的最簡單的解決方案是像這樣擴展 class 秒表:
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;
}
}
目前我對這段代碼的要求並不多。 只需在某個時間點啟動秒表,然后繼續運行。 它可以很容易地擴展到 class 秒表的其他get
類型。
這就是我打算如何使用 class
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();
}
想玩代碼,還是測試一下? 點擊這里
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.