Flutter:为什么我不能创建一个全为 0 值的 DateTime 对象?
所以我想在 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
}
正如您所看到的,我首先尝试使用 DateTime 对象来跟踪时间。
但是 DateTime(0, 0, 0, 0, 0, 0, 0, 0)
初始化为 -0001-11-30 00:00:00.000
。在我尝试添加 1 秒后,该值不会更新,它总是打印出相同的结果。
去 dartpad 通过运行此代码:
DateTime elapsedTime = DateTime(0, 0, 0, 0, 0, 0, 0, 0);
print(elapsedTime);
elapsedTime.add(Duration(seconds: 1));
print(elapsedTime);
有谁知道为什么会发生这种情况?
现在我将只使用 int 来跟踪时间并自己进行格式化。
PS,如果有人想要代码,我就是这样做的:
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';
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';
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以尝试以下操作:
注意:日和月的最小值是 1 而不是 0。
You can try this:
Note: The lowest value for day and month is 1 and not 0.