I have a stopwatch and would like to have a single button that both pauses and starts it. I am struggling with the logic around this. When printing to the console, the boolean is stuck on false, and won't let me re-click the button.
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";
}
}
When the first button is clicked the first time, the stopwatch should start running. When it is clicked the second time, it should pause it.