こんにちは。
今回は、経過時間を測る方法を紹介します。
方法
経過時間を測るには、Stopwatchクラスを使います。
まず、Stopwatchのインスタンスを用意します。
次に、Stopwatchの次のメソッドを使い、経過時間を測ります。
- start() : 時間を測り始める
- stop() : 時間を測るのをやめる
- reset() : 時間をリセットする
最後に、次のプロパティを使って時間を確認します。
- elapsed : 経過時間
- elapsedMicroSeconds : 経過時間(マイクロ秒)
- elapsedMilliSeconds : 経過時間(ミリ秒)
使用例
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
Stopwatch _timer = Stopwatch(); //Stopwatchのインスタンス
String duration = '';
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text("Time; ${_timer.elapsed}"), //経過時間
ElevatedButton(
onPressed: () {
setState(() {
if (_timer.isRunning) {
duration = _timer.elapsedTicks.toString(); //
_timer.stop();
} else {
_timer.start();
}
});
},
child: Text(_timer.isRunning ? 'Sto![ストップウォッチ.gif](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/3524120/86e6cad3-0ff8-fbcb-e6a7-759eb253b1cf.gif)
p' : 'Start'),
)
],
),
),
);
}
}
実行例
最後に
ここまで読んでいただき、ありがとうございました!
いいねしてくれたら、スキップして喜びます