我想在“每周优惠”部分中使用以下示例代码,但是我需要做两件事:
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,
),
),
],
),
);
}
}
答案 0 :(得分:1)
如果我错了,请纠正我,但是您正在寻找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。
如果我误解了您的要求,请随时告诉我,我会尽力回答!