So I want to make a Stopwatch in Flutter.
static void startTrip() {
SharedPrefsHelper().setIsCurrentlyOnTrip(true);
_elapsedTime = DateTime(
0, //year
0, //month
0, //day
0, //hour
0, //minute
0, //second
0, //millisecond
0, //microsecond
);
_timer = Timer.periodic(Duration(seconds: 1), (Timer timer) {
_elapsedTime.add(Duration(seconds: 1));
print('new time: $_elapsedTime');
_controller.sink.add(_elapsedTime); //same object/reference, but this is for the StreamBuilder to update
});
//TODO
}
As you can see I first attempted to use a DateTime object to keep track of the time.
But DateTime(0, 0, 0, 0, 0, 0, 0, 0)
initializes to -0001-11-30 00:00:00.000
. And the value doesn't update after I try to add 1 second, it always prints out the same.
Go and try it out your self on dartpad by running this code:
DateTime elapsedTime = DateTime(0, 0, 0, 0, 0, 0, 0, 0);
print(elapsedTime);
elapsedTime.add(Duration(seconds: 1));
print(elapsedTime);
Does anyone know why this happens?
For now I will just use an int to keep track of the time instead and do the formatting myself.
P.S so this is how I did it, if anyone wants the code:
int hours = elapsedTime ~/ 3600;
int minutes = (elapsedTime % 3600) ~/ 60; //get rid of all additional hours, then divide by 60
int seconds = elapsedTime % 60; //get rid of all additional minutes
String h = hours > 9 ? hours.toString() : '0$hours';
String m = minutes > 9 ? minutes.toString() : '0$minutes';
String s = seconds > 9 ? seconds.toString() : '0$seconds';
CodePudding user response:
You can try this:
DateTime elapsedTime = DateTime.utc(0);
print(elapsedTime);
elapsedTime = elapsedTime.add(Duration(seconds: 1));
print(elapsedTime);
Note: The lowest value for day and month is 1 and not 0.