【flutter】ストップウォッチ機能の作り方
ストップウォッチ機能を実装したかったのですが、日本語記事で初学者にとってわかりやすいものがないな〜と感じたので共有します。
参考にしたもの
完成形
Start
Stop
Reset
実装
providerを採用しましたので、ファイルは2つ用意します。
1.stop_watch
2.stop_watch_model
stop_watch.dart
body: Container(
padding: const EdgeInsets.all(30.0),
child: ChangeNotifierProvider<StopWatchModel>(
create: (_) => StopWatchModel(),
child: Consumer<StopWatchModel>(
builder: (context, model, child) {
return Column(
children: [
const SizedBox(height: 100.0),
Container(
alignment: Alignment.center,
child: Text(
model.stopWatchTimeDisplay,
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 50.0,
),
),
),
const SizedBox(height: 30.0),
Row(
children: [
Padding(
padding: const EdgeInsets.only(left: 50, right: 8),
child: RaisedButton(
color: Colors.redAccent,
child: const Text('STOP'),
onPressed: model.isStopPressed ? null : model.stopStopWatch,
),
),
Padding(
padding: const EdgeInsets.only(
left: 30,
right: 8,
),
child: RaisedButton(
color: Colors.green,
child: const Text('RESET'),
onPressed: model.isResetPressed ? null : model.resetStopWatch,
),
),
],
),
const SizedBox(height: 20.0),
RaisedButton(
color: Colors.orange,
child: const Text('START'),
onPressed: model.isStartPressed ? model.startStopWatch : null,
)
],
);
},
),
),
),
stopWatchTimeDisplayが時間のテキストになります。
加えて三項演算子を使って、ボタンをアクティブにします。
stop_watch_model.dart
class StopWatchModel extends ChangeNotifier{
bool isStopPressed = true;
bool isResetPressed = true;
bool isStartPressed = true;
String stopWatchTimeDisplay = '00:00:00';
var swatch = Stopwatch();
final dul = const Duration(seconds: 1);
startTimer(){
Timer(dul,keepRunning);
}
keepRunning(){
if(swatch.isRunning){
startTimer();
}
this.stopWatchTimeDisplay = swatch.elapsed.inHours.toString().padLeft(2,"0") +':'
+ (swatch.elapsed.inMinutes%60).toString().padLeft(2,"0") +':'
+ (swatch.elapsed.inSeconds%60).toString().padLeft(2,"0") ;
notifyListeners();
}
startStopWatch() {
this.isStopPressed = false;
this.isStartPressed = true;
swatch.start();
startTimer();
notifyListeners();
}
stopStopWatch() {
this.isStopPressed = true;
this.isResetPressed = false;
swatch.stop();
notifyListeners();
}
resetStopWatch() {
this.isResetPressed = true;
this.isStartPressed = true;
swatch.reset();
stopWatchTimeDisplay = '00:00:00';
notifyListeners();
}
}
boolで状態を保持して、アクティブなボタンを変更させます。
ストップウォッチクラスを使いますので、ドキュメントは見ときましょう。