你能帮我解决这个代码吗?我做了一个计时器。
我希望计时器在其值为 1 时停止;
但事实并非如此。我不知道问题出在哪里。
请帮助我。谢谢你。
这是模拟器中的结果:
这是我的整个代码:
class _MyHomeState extends State<MyHome> {
double progress = 0;
void startTimer() {
Timer.periodic(const Duration(seconds: 1), (timer) {
setState(() {
if (progress == 1) {
timer.cancel();
} else {
progress += 0.1;
}
});
});
}
@override
Widget build(BuildContext context) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Stack(
alignment: Alignment.center,
children: [
Text(progress.toStringAsFixed(1)),
SizedBox(
height: 300,
width: 300,
child: CircularProgressIndicator(
value: progress,
color: Colors.deepOrange,
),
)
],
),
const SizedBox(
height: 50,
),
ElevatedButton(
onPressed: () {
setState(() {
progress = 0;
startTimer();
});
},
child: const Text('Start'))
],
),
);
}
}
这是因为浮点错误。在软件开发中,小数不能以 100% 的精度存储。您无法保证 0.1 + 0.1 = 0.2。这里的问题是
progress
永远不会等于 1。如果你在计时器的 else 分支中打印 progress
,你会看到它显示:
0.1
0.2
0.30000000000000004
0.4
0.5
0.6
0.7
0.7999999999999999
0.8999999999999999
0.9999999999999999
1.0999999999999999
1.2
1.3
要解决这个问题,只需检查它是否高于 0.9,例如这样
if (progress > 0.9) {
timer.cancel();
} else {
progress += 0.1;
}