【发布时间】:2019-12-17 19:40:51
【问题描述】:
我有一个秒表,想要一个按钮来暂停和启动它。我正在努力解决这个问题。打印到控制台时,布尔值卡在 false 上,不会让我重新单击按钮。
stopwatch.dart:
class NewStopWatch extends StatefulWidget {
@override
_NewStopWatchState createState() => new _NewStopWatchState();
}
class _NewStopWatchState extends State<NewStopWatch> {
Stopwatch watch = new Stopwatch();
Timer timer;
bool startStop = true;
String elapsedTime = '';
updateTime(Timer timer) {
if (watch.isRunning) {
setState(() {
startStop = false;
print("startstop Inside=$startStop");
elapsedTime = transformMilliSeconds(watch.elapsedMilliseconds);
});
}
}
@override
Widget build(BuildContext context) {
return new Container(
padding: EdgeInsets.all(20.0),
child: new Column(
children: <Widget>[
new Text(elapsedTime, style: new TextStyle(fontSize: 25.0)),
SizedBox(height: 20.0),
new Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new FloatingActionButton(
heroTag: "btn1",
backgroundColor: Colors.red,
onPressed: startOrStop(),
child: new Icon(Icons.pause)),
SizedBox(width: 20.0),
new FloatingActionButton(
heroTag: "btn2",
backgroundColor: Colors.green,
onPressed: resetWatch,
child: new Icon(Icons.check)),
],
)
],
));
}
startOrStop() {
print("startstop=$startStop");
if(startStop == true) {
startWatch();
} else {
stopWatch();
}
}
startWatch() {
startStop = true;
watch.start();
timer = new Timer.periodic(new Duration(milliseconds: 100), updateTime);
}
stopWatch() {
startStop = false;
watch.stop();
setTime();
startStop = true;
}
setTime() {
var timeSoFar = watch.elapsedMilliseconds;
setState(() {
elapsedTime = transformMilliSeconds(timeSoFar);
});
}
transformMilliSeconds(int milliseconds) {
int hundreds = (milliseconds / 10).truncate();
int seconds = (hundreds / 100).truncate();
int minutes = (seconds / 60).truncate();
int hours = (minutes / 60).truncate();
String hoursStr = (hours % 60).toString().padLeft(2, '0');
String minutesStr = (minutes % 60).toString().padLeft(2, '0');
String secondsStr = (seconds % 60).toString().padLeft(2, '0');
return "$hoursStr:$minutesStr:$secondsStr";
}
}
当第一次单击第一个按钮时,秒表应该开始运行。当它被第二次点击时,它应该暂停它。
【问题讨论】:
-
还没有回答您的解决方案,而是一些简单的问题:您为什么将布尔值命名为
startStop?知道true的值会导致什么结果是不必要的复杂。它应该启动还是停止计时器?还有,为什么要在stopWatch()中多次设置startStop? -
我最初将它设置为true,打算第一次单击按钮调用
startWatch()方法。stopWatch()中的不同值用于实验目的
标签: asynchronous flutter dart timer widget