我遵循了Flutter教程,该教程构建了一个秒表。
该应用会生成并运行,但是我无法更新该小部件的小时(HRS)和分钟(MIN)部分。只会更新秒(SEC)。
我尝试过移动代码片段并进行调试,但是最终我只是破坏了整个过程,因此根本无法运行。
以下是我的意思的屏幕截图:
这是应用程序:
mainActivity
反正有没有让它正常工作?
谢谢!
答案 0 :(得分:2)
您必须在setState
方法内添加所有更新的值,而不仅仅是几秒钟
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return new TimerAppState();
}
}
class TimerAppState extends State<MyApp> {
static const duration = const Duration(seconds: 1);
int secondsPassed = 0;
bool isActive = false;
Timer timer;
int seconds, minutes, hours;
@override
void initState() {
super.initState();
if (timer == null)
timer = Timer.periodic(duration, (Timer t) {
handleTick();
});
}
void handleTick() {
if (isActive) {
setState(() {
secondsPassed = secondsPassed + 1;
seconds = secondsPassed * 60;
minutes = secondsPassed ~/ 60;
hours = secondsPassed ~/ (60 * 60);
});
}
}
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter',
home: Scaffold(
appBar: AppBar(
title: Text('Flutter Timer'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
CustomTextContainer(
label: 'HRS', value: hours.toString().padLeft(2, '0')),
CustomTextContainer(
label: 'MIN',
value: minutes.toString().padLeft(2, '0')),
CustomTextContainer(
label: 'SEC',
value: seconds.toString().padLeft(2, '0')),
],
),
Container(
margin: EdgeInsets.only(top: 20),
child: RaisedButton(
child: Text(isActive ? 'STOP' : 'START'),
onPressed: () {
setState(() {
isActive = !isActive;
});
},
),
),
],
),
),
));
}
}
class CustomTextContainer extends StatelessWidget {
CustomTextContainer({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: new BoxDecoration(
borderRadius: new BorderRadius.circular(10),
color: Colors.black87,
),
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Text(
'$value',
style: TextStyle(
color: Colors.white, fontSize: 34, fontWeight: FontWeight.bold),
),
Text(
'$label',
style: TextStyle(
color: Colors.white70,
),
)
],
),
);
}
}
答案 1 :(得分:0)
使用som模数%
int seconds = secondsPassed % 60;
int minutes = secondsPassed ~/ 60 % 60;
int hours = secondsPassed ~/ (60 * 60) % 24;