[英]make reverse countdown timer in flutter
我想在每周优惠部分使用以下示例代码,但我需要两件事:
1- 在我的计时器中添加计数日 2- 我想反向启动计时器,例如我想使用它一周,这意味着倒计时 7 天,当它完成后,再次在 7 天后自动启动......如何我可以用这个代码来做吗? 谢谢你。
import 'package:flutter/material.dart';
import 'dart:async';
class TimerWeek extends StatefulWidget {
@override
_TimerWeekState createState() => _TimerWeekState();
}
class _TimerWeekState extends State<TimerWeek> {
static const duration = const Duration(seconds: 1);
int secondPassed = 0;
bool isActive = false;
Timer timer;
void handleTick() {
if (isActive) {
setState(() {
secondPassed = secondPassed + 1;
});
}
}
@override
Widget build(BuildContext context) {
if (timer == null) {
timer = Timer.periodic(duration, (Timer t) {
handleTick();
});
}
int seconds = secondPassed % 60;
int minutes = secondPassed ~/ 60;
int hours = secondPassed ~/ (60 * 60);
return Container(
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
LabelText(label: '', value: hours.toString().padLeft(2, '0')),
LabelText(label: '', value: minutes.toString().padLeft(2, '0')),
LabelText(label: '', value: seconds.toString().padLeft(2, '0')),
],
),
SizedBox(height: 30),
Container(
width: 200,
height: 47,
margin: EdgeInsets.only(top: 30),
child: RaisedButton(
color: Colors.pink[200],
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(25)),
child: Text(isActive ? 'STOP' : 'START'),
onPressed: () {
setState(() {
isActive = !isActive;
});
},
),
)
],
),
);
}
}
class LabelText extends StatelessWidget {
LabelText({this.label, this.value});
final String label;
final String value;
@override
Widget build(BuildContext context) {
return Container(
margin: EdgeInsets.symmetric(horizontal: 5),
padding: EdgeInsets.all(20),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(25),
color: Colors.teal,
),
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Text(
'$value',
style: TextStyle(
color: Colors.white, fontSize: 12, fontWeight: FontWeight.bold),
),
Text(
'$label',
style: TextStyle(
color: Colors.white70,
),
),
],
),
);
}
}
如果我错了,请纠正我,但您正在寻找 1 周倒计时计时器? 此时,您的计时器中似乎已经有小时、分钟和秒数,因此您只需添加天数、一周,然后从那里计算 timeLeft。
int days = secondPassed ~/ (86400);
int const week = 604800; // number of seconds in a week
int timeLeft = week - secondPassed;
int daysLeft = timeLeft ~/ (86400);
int hoursLeft = (timeLeft - (daysLeft * 86400)) ~/ (3600); //number of seconds in an hour
int minutesLeft = (timeLeft - (daysLeft * 86400) - (hoursLeft * 3600)) ~/ (60);
int secondsLeft = (timeLeft - (daysLeft * 86400) - (hoursLeft * 3600) - (minutesLeft * 60)) % (60);
通过这种方式,您将获得一周剩余的秒、分、小时和天数,然后只需添加一个 IF 语句块来测试 timeLeft = 0,然后再次将计时器重置为 604800。
如果我误解了您的要求,请随时告诉我,我会尽力回答!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.