试图显示一个静态计时器,该计时器根据当前东部时间每周重置一次,例如屏幕上显示计时器Days : Hours : Minutes : seconds
(示例:7: 00 : 00 : 00
)倒计时并在最后重置自己每个星期日或星期一开始。我有一个笼统的概念,它涉及DateTime
,Timer
和Stopwatch
,但很难将它们放在一起。
答案 0 :(得分:2)
创建一个Timer
来获取和存储您的build
更新时的当前时间。在import 'dart:async';
import 'package:flutter/material.dart';
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Week Countdown',
home: TestPage(),
);
}
}
class TestPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Week Countdown')),
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Text(
'Time until next week:',
style: Theme.of(context).textTheme.headline,
),
WeekCountdown()
],
),
),
);
}
}
class WeekCountdown extends StatefulWidget {
@override
State<StatefulWidget> createState() => _WeekCountdownState();
}
class _WeekCountdownState extends State<WeekCountdown> {
Timer _timer;
DateTime _currentTime;
@override
void initState() {
super.initState();
_currentTime = DateTime.now();
_timer = Timer.periodic(Duration(seconds: 1), _onTimeChange);
}
@override
void dispose() {
_timer.cancel();
super.dispose();
}
void _onTimeChange(Timer timer) {
setState(() {
_currentTime = DateTime.now();
});
}
@override
Widget build(BuildContext context) {
final startOfNextWeek = calculateStartOfNextWeek(_currentTime);
final remaining = startOfNextWeek.difference(_currentTime);
final days = remaining.inDays;
final hours = remaining.inHours - remaining.inDays * 24;
final minutes = remaining.inMinutes - remaining.inHours * 60;
final seconds = remaining.inSeconds - remaining.inMinutes * 60;
final formattedRemaining = '$days : $hours : $minutes : $seconds';
return Text(formattedRemaining);
}
}
DateTime calculateStartOfNextWeek(DateTime time) {
final daysUntilNextWeek = 8 - time.weekday;
return DateTime(time.year, time.month, time.day + daysUntilNextWeek);
}
方法中,计算时间差并设置其格式:
{{1}}